PHP - Check if string contains illegal chars in string - php

In JS you can do:
var chs = "[](){}";
var str = "hello[asd]}";
if (str.indexOf(chs) != -1) {
alert("The string can't contain the following characters: " + chs.split("").join(", "));
}
How can you do this in PHP (replacing alert with echo)?
I do not want to use a regex for the simplicity of what I think.
EDIT:
What I've tried:
<?php
$chs = /[\[\]\(\)\{\}]/;
$str = "hella[asd]}";
if (preg_match(chs, str)) {
echo ("The string can't contain the following characters: " . $chs);
}
?>
Which obviously doesn't work and idk how to do it without regex.

In php you should do this:
$string = "Sometring[inside]";
if(preg_match("/(?:\[|\]|\(|\)|\{|\})+/", $string) === FALSE)
{
echo "it does not contain.";
}
else
{
echo "it contains";
}
The regex says check to see any of the characters are inside the string. you can read more about it here:
http://en.wikipedia.org/wiki/Regular_expression
And about PHP preg_match() :
http://php.net/manual/en/function.preg-match.php
Update:
I have written an updated regex for this, which captures the letters inside:
$rule = "/(?:(?:\[([\s\da-zA-Z]+)\])|\{([\d\sa-zA-Z]+)\})|\(([\d\sa-zA-Z]+)\)+/"
$matches = array();
if(preg_match($rule, $string, $matches) === true)
{
echo "It contains: " . $matches[0];
}
It returnes something like this:
It contains: [inside]
I have changed the regex only which becomes:
$rule = "/(?:(?:(\[)(?:[\s\da-zA-Z]+)(\]))|(\{)(?:[\d\sa-zA-Z]+)(\}))|(\()(?:[\d\sa-zA-Z]+)(\))+/";
// it returns an array of occurred illegal characters
It now returns [] for this "I am [good]"

Why not you try str_replace.
<?php
$search = array('[',']','{','}','(',')');
$replace = array('');
$content = 'hella[asd]}';
echo str_replace($search, $replace, $content);
//Output => hellaasd
?>
Instead of regex we can use string replace for this case.

here is a simple solution without using regex:
$chs = array("[", "]", "(", ")", "{", "}");
$string = "hello[asd]}";
$err = array();
foreach($chs AS $key => $val)
{
if(strpos($string, $val) !== false) $err[]= $val;
}
if(count($err) > 0)
{
echo "The string can't contain the following characters: " . implode(", ", $err);
}

Related

Detect quotes with in quotes using RegEx

I am looking for a way to detect and drop quotes with in quotes, for example: something "something "something something" something" something.
In the above example the italic something something is wrapped in double-quotes as you can see. I want to strip the string inside from these outer quotes.
So, the expression should simply look for quotes with a text between them plus a another set of text-wrapping text, and then drop the quotes wrapping the last.
This is my current code (php):
preg_match_all('/".*(".*").*"/', $text, $matches);
if(is_array($matches[0])){
foreach($matches[0] as $match){
$text = str_replace($match, '"' . str_replace('"', '', $match) . '"', $text);
}
}
If the string starts with a " and the double quotes inside the string are always balanced you might use:
^"(*SKIP)(*F)|"([^"]*)"
That would match a double quote at the start of the string and then skips that match using SKIP FAIL. Then it would match ", capture in a group what is between the " and match a " again.
In the replacement you could use capturing group 1 $1
$pattern = '/^"(*SKIP)(*F)|"([^"]+)"/';
$str = "\"something \"something something\" and then \"something\" something\"";
echo preg_replace($pattern, "$1", $str);
"something something something and then something something"
Demo
You could leverage strpos() with the third parameter (offset) to look up all quotes and replace every quote from 1 to n-1:
<?php
$data = <<<DATA
something "something "something something" something" something
DATA;
# set up the needed variables
$needle = '"';
$lastPos = 0;
$positions = array();
# find all quotes
while (($lastPos = strpos($data, $needle, $lastPos)) !== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
# replace them if there are more than 2
if (count($positions) > 2) {
for ($i=1;$i<count($positions)-1;$i++) {
$data[$positions[$i]] = "";
}
}
# check the result
echo $data;
?>
This yields
something "something something something something" something
You could even hide it in a class:
class unquote {
# set up the needed variables
var $data = "";
var $needle = "";
var $positions = array();
function cleanData($string="", $needle = '"') {
$this->data = $string;
$this->needle = $needle;
$this->searchPositions();
$this->replace();
return $this->data;
}
private function searchPositions() {
$lastPos = 0;
# find all quotes
while (($lastPos = strpos($this->data, $this->needle, $lastPos)) !== false) {
$this->positions[] = $lastPos;
$lastPos = $lastPos + strlen($this->needle);
}
}
private function replace() {
# replace them if there are more than 2
if (count($this->positions) > 2) {
for ($i=1;$i<count($this->positions)-1;$i++) {
$this->data[$this->positions[$i]] = "";
}
}
}
}
And call it with
$q = new unquote();
$data = $q->cleanData($data);

Find words in text, php

How to resolve this problem:
Write a PHP program that finds the word in a text.
The suffix is separated from the text by a pipe.
For example: suffix|SOME_TEXT;
input: text|lorem ips llfaa Loremipsumtext.
output: Loremipsumtext
My code is this, but logic maybe is wrong:
$mystring = fgets(STDIN);
$find = explode('|', $mystring);
$pos = strpos($find, $mystring);
if ($pos === false) {
echo "The string '$find' was not found in the string '$mystring'.";
}
else {
echo "The string '$find' was found in the string '$mystring',";
echo " and exists at position $pos.";
}
explode() returns an array, so you need to use $find[0] for the suffix, and $find[1] for the text. So it should be:
$suffix = $find[0];
$text = $find[1];
$pos = strpos($text, $suffix);
if ($pos === false) {
echo "The string '$suffix' was not found in '$text'.";
} else {
echo "The string '$suffix' was found in '$text', ";
echo " and exists at position $pos.";
}
However, this returns the position of the suffix, not the word containing it. It also doesn't check that the suffix is at the end of the word, it will find it anywhere in the word. If you want to match words rather than just strings, a regular expression would be a better method.
$suffix = $find[0];
$regexp = '/\b[a-z]*' . $suffix . '\b/i';
$text = $find[1];
$found = preg_match($regexp, $text, $match);
if ($found) {
echo echo "The suffix '$suffix' was found in '$text', ";
echo " and exists in the word '$match[0]'.";
} else {
echo "The suffix '$suffix' was not found in '$text'.";
}

Matching string in 2 different patterns in PHP. The code must return TRUE

Objective: strings with ' should match the string without it.
Example:
$first_string = "alex ern o'brian";
$second_string = "alex-ern o brian";
$pattern = array("/(-|\.| )/", "/(')/");
$replace = array(' ', '(\s|)');
$first_string = preg_replace($pattern, $replace, $first_string);
$second_string = preg_replace($pattern, $replace, $second_string);
$first_string_split = preg_split("/(-|\.| )/", $first_string);
$first_string_split[] = $first_string;
$second_string_split = preg_split("/(-|\.| )/", $second_string);
$second_string_split[] = $second_string;
$first_string = array_slice($first_string_split, -1)[0];
$second_string = array_slice($second_string_split, -1)[0];
if(in_array($first_string, $second_string_split) || in_array($second_string, $first_string_split))
{
echo 'true';
} else {
echo 'false';
}
I think you are expecting this.
Solution 1: Try this code snippet here
Regex: (\s|) this will match either space or null.
<?php
ini_set('display_errors', 1);
$string = "o'brian";
$string=str_replace("'", "(\s|)",$string);
$list = array("o'neal", "o brian", "obrian");
$result=array();
foreach($list as $value)
{
if(preg_match("/$string/", $value))
{
$result[]=$value;
}
}
print_r($result);
Solution 2:
Regex: [a-z]+ will match character from a to z.
$string1="o brian";
$string2="obrian";
if(preg_match("/".implode(" ", $matches[0])."/", $string1))
{
echo "matched";
}
if( preg_match("/".implode("", $matches[0])."/", $string2))
{
echo "matched";
}
I'm not sure if I got your question right, but this should do it:
(?<=\w)'(?=\w)
It matches every ' character, which is followed and preceded by a word character. The word character \w is equal to [a-zA-Z0-9_].
Here is a live example to test the regex
Here is a live PHP example

php extract a sub-string before and after a character from a string

need to extract an info from a string which strats at 'type-' and ends at '-id'
IDlocationTagID-type-area-id-492
here is the string, so I need to extract values : area and 492 from the string :
After 'type-' and before '-id' and after 'id-'
You can use the preg_match:
For example:
preg_match("/type-(.\w+)-id-(.\d+)/", $input_line, $output_array);
To check, you may need the service:
http://www.phpliveregex.com/
P.S. If the function preg_match will be too heavy, there is an alternative solution:
$str = 'IDlocationTagID-type-area-id-492';
$itr = new ArrayIterator(explode('-', $str));
foreach($itr as $key => $value) {
if($value === 'type') {
$itr->next();
var_dump($itr->current());
}
if($value === 'id') {
$itr->next();
var_dump($itr->current());
}
}
This is what you want using two explode.
$str = 'IDlocationTagID-type-area-id-492';
echo explode("-id", explode("type-", $str)[1])[0]; //area
echo trim(explode("-id", explode("type-", $str)[1])[1], '-'); //492
Little Simple ways.
echo explode("type-", explode("-id-", $str)[0])[1]; // area
echo explode("-id-", $str)[1]; // 492
Using Regular Expression:
preg_match("/type-(.*)-id-(.*)/", $str, $output_array);
print_r($output_array);
echo $area = $output_array[1]; // area
echo $fnt = $output_array[2]; // 492
You can use explode to get the values:
$a = "IDlocationTagID-type-area-id-492";
$data = explode("-",$a);
echo "Area ".$data[2]." Id ".$data[4];
$matches = null;
$returnValue = preg_match('/type-(.*?)-id/', $yourString, $matches);
echo($matches[1]);

How to find out if there is any redundant word in string in php?

I need to find out if there are any redundant words in string or not .Is there any function that can provide me result in true/false.
Example:
$str = "Hey! How are you";
$result = redundant($str);
echo $result ; //result should be 0 or false
But for :
$str = "Hey! How are are you";
$result = redundant($str);
echo $result ; //result should be 1 or true
Thank you
You could use explode to generate an array containing all words in your string:
$array = explode(" ", $str);
Than you could prove if the arrays contains duplicates with the function provided in this answer:
https://stackoverflow.com/a/3145660/5420511
I think this is what you are trying to do, this splits on punctuation marks or whitespaces. The commented out lines can be used if you want the duplicated words:
$str = "Hey! How are are you?";
$output = redundant($str);
echo $output;
function redundant($string){
$words = preg_split('/[[:punct:]\s]+/', $string);
if(max(array_count_values($words)) > 1) {
return 1;
} else {
return 0;
}
//foreach(array_count_values($words) as $word => $count) {
// if($count > 1) {
// echo '"' . $word . '" is in the string more than once';
// }
//}
}
References:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php
Regex Demo: https://regex101.com/r/iH0eA6/1

Categories