preg_match not working with ^ and $ - php

I use preg_match for testing unicode pattern with symbols and digits.
$reg = '/^(?=.*\p{L})[\d\p{L}]+$/im';
$str = trim('станция44');
if (preg_match($reg, $str) === 1) {
echo 'Match';
} else {
echo 'Not match';
}
If I test it I get Not match but if I remove ^ and $ I get Match. Why it is happen?

Because you're using p{L} matching you need to add the Unicode modifier (u) at the end:
$reg = '/^(?=.*\p{L})[\d\p{L}]+$/imu';
More info: http://php.net/manual/en/regexp.reference.unicode.php

Related

Compare username to regular expression with PHP

I've never used regular expressions before and did some research on how to allow my username field only alphanumeric characters, dashes, dots, and underscores. I have the following expression but it doesn't seem to be working.
$string = "Joe_Scotto";
if (!preg_match('[a-zA-Z0-9_-.]', $string)) {
echo "Does not match Regex";
} else {
echo "Matches";
}
I want the statement to return true if it is following the "guidelines" and false if the username contains something other than what I specified it should contain. Any help would be great. Thanks!
Try this
$string = "Joe_Scotto";
if (!preg_match('/^[A-Za-z0-9_.]+$/', $string)) {
echo "Does not match Regex";
} else {
echo "Matches";
}
You match only a single character. Try this:
$string = "Joe_Scotto";
if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $string)) {
echo "Does not match Regex";
} else {
echo "Matches";
}
The + sign says: match 1 or more characters defined directly before the + (* is the same but matches 0 or more characters).
Also the separators '/' (or any other separator characters) are required.
And in character classes, it is better to place the - sign to the end, else it could be misinterpreted as range from _ to .
And add ^ at the beginning (this means: match from the beginning of the input) and $ to the end (this means: match to the end of the input). Else, also a part of the string would match.
You should use something like that http://www.phpliveregex.com/p/ern
$string = 'John_Buss';
if (preg_match('/[A-z0-9_\-.]+/', $string)) {
return true;
} else {
return false;
}
Make sure to add / delimiter character at the start and the end of your regex
Make sure to use \ escape character before -
Make sure to add + character quantifier

Check if string contains the same pattern

How can I check if a string has a specific pattern like this?
XXXX-XXXX-XXXX-XXXX
4 alphanumeric characters then a minus sign, 4 times like the structure above.
What I would like to do is that I would like to check if a string contains this structure including "-".
I'm lost, can anyone point me in the correct direction?
Example code:
$string = "5E34-4512-ABAX-1E3D";
if ($pattern contains this structure XXXX-XXXX-XXXX-XXXX) {
echo 'The pattern is correct.';
}
else {
echo 'The pattern is invalid.';
}
Use regular expressions
<?php
$subject = "XXXX-XXXX-XXXX-XXXX";
$pattern = '/^[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}$/';
if(preg_match($pattern, $subject) == 1);
echo 'The pattern is correct.';
} else {
echo 'The pattern is invalid.';
}
?>
[a-zA-Z0-9] match a single character
{4} matches the character Exactly 4 times
\- matches a escaped hyphen
With a perl regexp :
$string = "5E34-4512-ABAX-1E3D";
if (preg_match('/\w{4}-\w{4}-\w{4}-\w{4}/',$string)) {
echo 'The pattern is correct.';
}
use preg_match :
$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/', $string)
And if you want to consider lowercase characters, use :
$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/i', $string)

preg_match: can't find substring which has trailing special characters

I have a function which uses preg_match to check for if a substring is in another string.
Today I realize that if substring has trailing special characters like special regular expression characters (. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -) or #, my preg_match can't find the substring even though it is there.
This works, returns "A match was found."
$find = "website scripting";
$string = "PHP is the website scripting language of choice.";
if (preg_match("/\b" . $find . "\b/i", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
But this doesn't, returns "A match was not found."
$find = "website scripting #";
$string = "PHP is the website scripting # language of choice.";
if (preg_match("/\b" . $find . "\b/i", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
I have tried preg_quote, but it doesn't help.
Thank you for any suggestions!
Edit: Word boundary is required, that's why I use \b. I don't want to find "phone" in "smartphone".
You can just check if the characters around the search word are not word characters with look-arounds:
$find = "website scripting #";
$string = "PHP is the website scripting # language of choice.";
if (preg_match("/(?<!\\w)" . preg_quote($find, '/') . "(?!\\w)/i", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
See IDEONE demo
Result: A match was found.
Note the double slash used with \w in (?<!\\w) and (?!\\w), as you have to escape regex special characters in interpolated strings.
The preg_quote function is necessary as the search word - from what I see - can have special characters, and some of them must be escaped if intended to be matched as literal characters.
UPDATE
There is a way to build a regex with smartly placed word boundaries around the keyword, but the performance will be worse compared with the approach above. Here is sample code:
$string = "PHP is the website scripting # language of choice.";
$find = "website scripting #";
$find = preg_quote($find);
if (preg_match('/\w$/u', $find)) { // Setting trailing word boundary
$find .= '\\b';
}
if (preg_match('/^\w/u', $find)) { // Setting leading word boundary
$find = '\\b' . $find;
}
if (preg_match("/" . $find . "/ui", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
See another IDEONE demo
If you try to find a string from another string, you can strpos().
Ex.
<?php
$find = "website scripting";
$string = "PHP is the website scripting language of choice.";
if (strpos($string,$find) !== false) {
echo 'true';
} else {
echo 'false';
}

preg_match issues using php variable

I have a variable I want to use in a preg_match combined with some regex:
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-/d.*/", $string)) {
echo "matched";
}
In my pattern I am trying to match using cheese, followed by a - and 1 digit, followed by anything else.
change /d to \d
there is no need to use .*
if your string is defined by user (or may contains some characters (e.g: / or * or ...)) this may cause problem on your match.
Code:
<?php
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-\d/", $string))
{
echo "matched";
}
?>
You mistyped / for \:
if(preg_match("/$find-\d.*/", $string)) {
The .* is also not really necessary since the pattern will match either way.
for digit, it's \d
if(preg_match("/$find-\d.*/", $string)) {

Allow only [a-z][A-Z][0-9] in string using PHP

How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?
You can filter it like:
$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);
As for some symbols, you should be more specific
You can test your string (let $str) using preg_match:
if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
// string only contain the a to z , A to Z, 0 to 9
}
If you need more symbols you can add them before ]
Don't need regex, you can use the Ctype functions:
ctype_alnum: Check for alphanumeric character(s)
ctype_alpha: Check for alphabetic character(s)
ctype_cntrl: Check for control character(s)
ctype_digit: Check for numeric character(s)
ctype_graph: Check for any printable character(s) except space
ctype_lower: Check for lowercase character(s)
ctype_print: Check for printable character(s)
ctype_punct: Check for any printable character which is not whitespace or an alphanumeric character
ctype_space: Check for whitespace character(s)
ctype_upper: Check for uppercase character(s)
ctype_xdigit: Check for character(s) representing a hexadecimal digit
In your case use ctype_alnum, example:
if (ctype_alnum($str)) {
//...
}
Example:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo 'The string ', $testcase, ' consists of all letters or digits.';
} else {
echo 'The string ', $testcase, ' don\'t consists of all letters or digits.';
}
}
Online example: https://ideone.com/BYN2Gn
Both these regexes should do it:
$str = preg_replace('~[^a-z0-9]+~i', '', $str);
Or:
$str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);
A shortcut will be as below also:
if (preg_match('/^[\w\.]+$/', $str)) {
echo 'Str is valid and allowed';
} else
echo 'Str is invalid';
Here:
// string only contain the a to z , A to Z, 0 to 9 and _ (underscore)
\w - matches [a-zA-Z0-9_]+
Hope it helps!
If you need to preserve spaces in your string do this
$text = preg_replace("/[^a-zA-Z0-9 ]+/", "", $text);
Please note the way I have added space between 9 and the closing bracket. For example
$name = "!#$John Doe";
echo preg_replace("/[^a-zA-Z0-9 ]+/", "", $name);
the output will be:
John Doe
Spaces in the string will be preserved.
If you fail to include the space between 9 and the closing bracket the output will be:
JohnDoe
Hope it helps someone.
The best and most flexible way to accomplish that is using regular expressions.
But I`m not sure how to do that in PHP but this article can help. link

Categories