I'm trying to find special characters with characters like <?, <?php, or ?> in a string. The code below works to find "php" in the string anywhere no matter if it's PHP, php, or phpaPHPa.
<?php
$searchfor = "php";
$string = "PHP is the web scripting language of choice.";
if (preg_match("/".$searchfor."/i", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
I need a similar code that finds special characters like <?, <?php, or ?> in the string. Any suggestions?
You can use same code. Just make sure to escape regex special characters when using them in matching. The question mark must be escaped so your $searchfor becomes <\?php
Using strpos (or stripos) will be faster than using RegEx'es...
if(false === strpos($text, '<?'))
echo 'Match was not found';
else
echo 'Match was found';
Related
Hi why is the preg_match with brackets and determined string is not working?
Pls let me know your solution to search for "uRole('Admin')".
<?php
$check ='if(uRole("Admin")||uRole("Design")){';
preg_match('/uRole("Admin")/i', $check)? echo 'match':"";
?>
Two reasons this isn't working...
You have to escape () in REGEX (otherwise it's assuming a group)
You don't use echo in a ternary operator; it has to come before
echo (STATEMENT_TO_EVALUATE = [TRUE | FALSE]) : TRUE_VALUE : FALSE_VALUE;
Working code
$check ='if(uRole("Admin")||uRole("Design")){';
echo preg_match('/uRole\("Admin"\)/i', $check, $matches) ? "match" : "";
That is because the ( and ) is a special character in regular expressions used to create groups.
Because it is a special character, you should use a backslash to escape it:
if (preg_match('/uRole\("Admin"\)/i', $check)) {
echo 'match';
}
By the way, in this situation a simple stripos is probably more appropriate:
if (stripos($check, 'uRole("Admin")') !== false) {
echo 'match';
}
I have a strange question maybe you could help me with. I am trying to check whether the given string contains special characters. The code below is working however one character seems to get exempted on the condition which is the square brackets [ ]. Can you help me with this? thank you.
$string = 'starw]ars';
if (preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $string)) {
echo 'Output: Contains Special Characters';
}else{
echo 'Output: valid characters';
}
Please note: I can't use below condition since I need to accept others characters from other languages like in arabic, chinese, etc. so it means I need to specify all characters that is not allowed.
if (!preg_match('/[^A-Za-z0-9]/', $string))
Appreciate your help. Thanks.
You forgot to add square brackets [] in your expression. I have added this \[\] in your current expression.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string = 'starw]ars';
if (preg_match('/[\[\]\'^£$%&*()}{##~?><>,|=_+¬-]/', $string))
{
echo 'Output: Contains Special Characters';
} else
{
echo 'Output: valid characters';
}
Use strpos:
$string = 'starw]ars';
if (strpos($string, ']') !== false) {
echo 'true';
}
Please see the following answer for additional information:
How do I check if a string contains a specific word in PHP?
You should add escaped square brackets to your expression.
preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-\[\]]/', $string)
EDIT: Apologies to #Thamilan, I didn't see your comment.
EDIT 2: You could also use the preg_quote function.
preg_match(preg_quote('\'^£$%&*()}{##~?><>,|=_+¬-[]', '/'), $string);
The preg_quote function will escape your special characters for you.
Try this example:
<?php
$string = 'starw]]$%ars';
if (preg_match('/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/', $string))
{
echo 'Output: Contains Special Characters';
} else
{
echo 'Output: valid characters';
}
?>
Output:
Output: Contains Special Characters
How to match any thing dosen't contain a specific word using RegExp
Ex:
Match any string doesn't contain 'aabbcc'
bbbaaaassdd // Match this
aabbaabbccaass // Reject this
If you're just after this sequence of characters, don't use a Regular Expression. Use strpos().
if (strpos('aabbaabbccaass', 'aabbcc') !== false) {
echo 'Reject this.'
}
Note: Be sure to read the warning in the manual about strpos() return values.
You can use negative lookahead:
(?!.*?aabbcc)^.*$
Live Demo: http://www.rubular.com/r/4Exbf7UdDv
PHP Code:
$str = 'aabbaabbccaass'; //or whatever
if (preg_match('/(?!.*?aabbcc)^.*$/', $str))
echo "accepted\n";
else
echo "rejected\n";
try this to avoid some sequences of letters :
^((?!aabbcc).)*$
try this:
if(preg_match('/aabbcc/', $string) == 0) {
[ OK ]
}
else {
[ NOT OK ]
}
You can use this to describe a substring that doesn't contain aabbcc:
(?>[^a]++|a(?!abbcc))*
for the whole string, just add anchors (^ $)
I am searching through text line by line and want to see if the line contains the phrase "see details" and is not case sensitive, so will find:
See Details, See details, SEE Details etc
I have this so far.
if(preg_match("/^(\see details)/", strtolower($line)))
{
echo 'SEE DETAILS FOUND';
}
A simple example would be helpful thanks.
If you want to check if a sub-string is present in a string, no need for regular expressions : stripos() will do just fine :
if (stripos(strtolower($line), 'see details') !== false) {
// 'see details' is in the $line
}
stripos() will return the position of the first occurrence of the sub-string in the string ; or false if the sub-string is not found.
Which means that if it returns something else than false, the sub-string is found.
Your regex is actually broken.
/^(\see details)/
This breaks down into:
At the beginning
Open a capturing group
Look for one whitespace character
Followed by all of the following characters: ee details
Close the group
\s is an escape sequence matching whitespace. You could also have added the i modifier to make the regex case-insensitive. You also don't seem to be doing anything with the captured group, so you can ditch that.
Therefore:
/^see details/i
is what you'd want.
You mentioned that you're going through input line by line. If you only need to know that the entire input contains the specific string, and you have the input as a string, you can use the m modifier to make ^ match "beginning of a line" instead of / in addition to "beginning of the string":
/^see details/im
If this is the case, then you would end up with:
if(preg_match('/^see details/im', $whole_input)) {
echo "See Details Found!";
}
But as others have mentioned, a regex isn't needed here. You can (and should) do the job with the more simple stripos.
As Pascal said, you can use stripos() function although correct code would be:
if (stripos(strtolower($line), 'see details') !== false) {
// 'see details' is in the $line
}
accoding to the php documentation (http://www.php.net/manual/en/function.preg-match.php):
<?php
/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
which it looks pretty simple and nice :-).
I have a text in MySQL database that is requested in "$description" and I would like to know if \\\\\\\\r\\\\\\\\n is present in the description. So i got:
if(strpos($description, "\\\\\\\\r\\\\\\\\n") !== FALSE) {
echo "String is here.";
} else {
echo "String not found.";
}
but this always outputs "String not found." and I believe there is a bad escaping in the searched string (\\\\\\\\r\\\\\\\\n). How can I strpos by \\\\\\\\r\\\\\\\\n ? Also, I would probably end up str_replace-ing every \\\\\\\\r\\\\\\\\n with \r\n as somebody made some bad escaping functions and data arrived as \\\\\\\\r\\\\\\\\n instead of \r\n, so a str_replace faces the same problem also. I could use help on any of these tasks (str_pos,str_replace).
Thank you very much.
The the unfortunate nature of the detecting the backslash character is because it is also the universal escaping character. And to put a literal backslash into a string, you have to escape it - with itself
That is to say, if you wanted to detect a single backslash, your code might look like this
if(strpos($description, '\\' ) !== FALSE)
Therefore, if you want to detect eight, consecutive backslashes, your string to match against will need double-that - sixteen.
if(strpos($description, '\\\\\\\\\\\\\\\\' ) !== FALSE)
Therefore, your final match using strpos() would have to look like this
if(strpos($description, '\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n' ) !== FALSE)
Also noticed that I switched to single-quotes. That's because \n and \r are interpreted inside of double-quoted string literals.
You can also do this with regular expressions, which is going to be a bit more flexible and powerful
if ( preg_match( "/\\x5C{8}[rn]/", $description ) )
EDIT
For search-replacing, I suggest something like this. As I mentioned above, the regular expression is going to be more powerful - this one will match \r or \n (and not just when they're adjacent) with ANY quantity of preceding backslashes, not only 8 of them.
$description = preg_replace( "/\\x5C+([rn])/", '\\\${1}', $description );
if(strpos($description, '\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n') !== FALSE) {
echo "String is here.";
} else {
echo "String not found.";
}
further reading
<?php
$in = "abc";
if(preg_match('/\n|\r/',$in)){
echo 'found';
}else{
echo 'not found';
}