preg_match whitespace problem - php

I need to write a regex but for some reason i cannot get the \s to find whitespace,
Im trying....
$name = "a ";
if( preg_match('^[a-z]+\s$', $name)){
echo "match";
} else {
echo "no match";
}
ive also tried
preg_match('^[a-z\s]+$');
and
preg_match('^[a-z]/\s/$');
Im just getting no match.
The full regex needs to allow 1 or more lowercase letters then a space then an uppercase letter followed by one or more lowercase, but....
preg_match('^[a-z]+\s[A-Z][a-z]+$');
isnt working as i'd expect it to going of the tutorials ive seen around the web (sitepoint etc...).
Anyone shed any light on it?

You have to add delimiters(docs) to the expressions:
$name = "a ";
if( preg_match('/^[a-z]+\s$/', $name)){
// ^ ^
// └----------┴----- here: slash as delimiter
echo "match";
} else {
echo "no match";
}
Here I used a slash / but you are pretty much free in choosing a delimiter (ok, not that much: any non-alphanumeric, non-backslash, non-whitespace character).
Make sure you have error reporting set to include warnings, e.g. by adding error_reporting(E_ALL). Then you would have seen this warning:
Warning: preg_match(): No ending delimiter '^' found in ... on line ...
no match
PHP treats the first character in the string as delimiter, so in your case the ^.

Related

PHP preg_match regular expression for find date in string

I try to make system that can detect date in some string, here is the code :
$string = "02/04/16 10:08:42";
$pattern = "/\<(0?[1-9]|[12][0-9]|3[01])\/\.- \/\.- \d{2}\>/";
$found = preg_match($pattern, $string);
if ($found) {
echo ('The pattern matches the string');
} else {
echo ('No match');
}
The result i found is "No Match", i don't think that i used correct regex for the pattern. Can somebody tell me what i must to do to fix this code
First of all, remove all gibberish from the pattern. This is the part you'll need to work on:
(/0?[1-9]|[12][0-9]|3[01]/)
(As you said, you need the date only, not the datetime).
The main problem with the pattern, that you are using the logical OR operators (|) at the delimiters. If the delimiters are slashes, then you need to replace the tube characters with escaped slashes (/). Note that you need to escape them, because the parser will not take them as control characters. Like this: \/.
Now, you need to solve some logical tasks here, to match the numbers correctly and you're good to go.
(I'm not gonna solve the homework for you :) )
These articles will help you to solve the problem tough:
Character classes
Repetition opetors
Special characters
Pipe character (alternation operator)
Good luck!
In your comment you say you are looking for yyyy, but the example says yy.
I made a code for yy because that is what you gave us, you can easily change the 2 to a 4 and it's for yyyy.
preg_match("/((0|1|2|3)[0-9])\/\d{2}\/\d{2}/", $string, $output_array);
Echo $output_array[1]; // date
Edit:
If you use this pattern it will match the time too, thus make it harder to match wrong.
((0|1|2|3)[0-9])/\d{2}/\d{2}\s+\d{2}:\d{2}:\d{2}
http://www.phpliveregex.com/p/fjP
Edit2:
Also, you can skip one line of code.
You first preg_match to $found and then do an if $found.
This works too:
If(preg_match($pattern, $string, $found))}{
Echo $found[1];
}Else{
Echo "nothing found";
}
With pattern and string as refered to above.
As you can see the found variable is in the preg_match as the output, thus if there is a match the if will be true.

Regex for Chinese / Japanese letters

Okai so I already have this regular expression for names allowed on my website.
However, I also wish to add other possible letters that names use.
Does someone have a good regex or know how I can make this more complete? I have searched for quite a while now, and I can't find anything that suits my needs.
This is my current regex for checking names:
$regex = "/^([a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'-])+$/";
if(preg_match($regex, $fullname)){
// do something
}
As Lucas Trzesniewski has mentioned, the \p{L} will include the [a-zA-Z], so I have removed from the pattern.
Thus, combining the character lists that you have included in the example; the pattern will look like this, /^[\p{L}\s,.'-]+$/u
^[]+$ matches the string from start to end, thus + also imply the need of matching one or more
\p{L} matches unicode characters
\s,.'- matches space, comma, period, single quotation, and dash
u the PCRE_UTF8 modifier, this modifier turns on additional functionality of PCRE that is incompatible with Perl.
if(preg_match("/^[\p{L}\s,.'-]+$/u", "お元気ですか你好吗how are you你好嗎,.'-") === 1) {
echo "match";
}
else {
echo "no match";
}
// match
if(preg_match("/^[\p{L}\s,.'-]+$/u", "お元気ですか你好吗how are you你好_嗎-,.'") === 1) {
echo "match";
}
else {
echo "no match";
}
// no match as there are underscore in 你好_嗎

PHP Regex Strip Away All Emojis

I am trying to strip away all non-allowed characters from a string using regex. Here is my current php code
$input = "👮";
$pattern = "[a-zA-Z0-9_ !##$%^&*();\\\/|<>\"'+\-.,:?=]";
$message = preg_replace($pattern,"",$input);
if (empty($message)) {
echo "The string is empty";
}
else {
echo $message;
}
The emoji gets printed out when I run this when I want it to print out "The string is empty.".
When I put my regex code into http://regexr.com/ it shows that the emoji is not matching, but when I run the code it gets printed out. Any suggestions?
This pattern should do the trick :
$filteredString = preg_replace('/([^-\p{L}\x00-\x7F]+)/u', '', $rawString);
Some sequences are quite rare, so let's explain them:
\p{L} matches any kind of letter from any language
\x00-\x7F a single character in the range between (index 0) and (index 127) (case sensitive)
the u modifier who turns on additional functionality of PCRE that is incompatible with Perl. Pattern and subject strings are treated as UTF-8.
Your pattern is incorrect. If you want to strip away all the characters that are not in the list provided, then you have to use a negating character class: [^...]. Also, currently, [ and ] are being used as delimiters, which means, the pattern isn't seen as a character class.
The pattern should be:
$pattern = "~[^a-zA-Z0-9_ !##$%^&*();\\\/|<>\"'+.,:?=-]~";
This should now strip away the emoji and print your message.

PHP regex to allow newline didn't work

PHP preg_match to accept new line
I want to pass every post/string through PHP preg_match function. I want to accept all the alpha-numerics and some special characters. Help me edit my syntax to allow newline. As the users fill textarea and press enter. Following syntax does not allow new line.
Please feedback whether following special characters are properly done or not
*/_:,.?#;-*
if (preg_match("/^[0-9a-zA-Z \/_:,.?#;-]+$/", $string)) {
echo 'good';
else {
echo 'bad';
}
You were almost there!
The DOTALL modifier mentioned by others is irrelevant to your regex.
To allow new lines, we just add \r\n to your character class. Your code becomes:
if (preg_match("/^[\r\n0-9a-zA-Z \/_:,.?#;-]+$/", $string)) {
echo 'good';
else {
echo 'bad';
}
Note that this test and the regex can be written in a tidier way:
echo (preg_match("~^[\r\n\w /:,.?#;-]+$~",$string))? "***Good!***" : "Bad!";
See the result of the online demo at the bottom.
\w matches letters, digits and underscores, so we can get rid of them in the character class
Changing the delimiter to a ~ allows you to use a / slash without escaping it (you need to escape delimiters)
it's always safe to add backslash to any non-alphanumeric characters so:
/^[0-9a-zA-Z \/\_\:\,\.\?\#\;\-]+$/
Also use character classes:
/^[[:alnum:] \/\_\:\,\.\?\#\;\-]+$/
oh about the new lines:
/^[[:alnum:] \r\n\/\_\:\,\.\?\#\;\-]+$/
to be able to do that string ^ (also, it'll be easier/safer to use single quotes)
'/^[[:alnum:] \\r\\n\/\_\:\,\.\?\#\;\-]+$/'
You can use an alternation to factor in the newlines:
/^(?:[0-9a-zA-Z \/_:,.?#;-]|\r?\n)+$/
Btw, you can shorten the expression a bit by replacing [A-Za-z0-9_] with [\w\d]:
/^(?:[\w\d \/:,.?#;-]|\r?\n)+$/
So:
if (preg_match('/^(?:[\w\d \/:,.?#;-]|\r?\n)+$/', $string)) {
echo "good";
} else {
echo "bad";
}

Match multiple delimiters containg backslashes php

I have a php code that needs to be matched for any of the following string using preg_match using this code
if(preg_match('/(image/gif)|(image/jpg)|(image/jpeg)/',$between))
{
echo "Match Found";
}
else
echo "Match Not Found";
but i get this error
Warning: preg_match() [function.preg-match]: Unknown modifier 'g' in C:\xampp\htdocs\project\extension.php on line 38
Any help will be appreciated....I googled alot but couldn't find solution...
You are using / as the delimiter character, so when it appears inside your regex you must escape it:
if(preg_match('/(image\/gif)|(image\/jpg)|(image\/jpeg)/',$between))
Alternatively, you can choose another delimiter:
if(preg_match('~(image/gif)|(image/jpg)|(image/jpeg)~',$between))
Replace your preg_match pattern with this:
'/(image\/gif)|(image\/jpg)|(image\/jpeg)/'
You should always escape characters like /
As long as you want / to be used inside regular expression - use ~ as a regex delimiter instead:
if(preg_match('~(image/gif)|(image/jpg)|(image/jpeg)~',$between))
^----------- ^--------
or even better:
if(preg_match('~image/(gif|jpe?g)~',$between))

Categories