I'm having the following reg-ex which is working fine for the normal string match against an array,
preg_grep( "/^". $name . "$/i", $values);
However its not working for the string which has special characters like "Entertainment (General)".
Find a related thread however its for java script and also it didn't help.
Use the preg_quote function to escape any special characters that might be in the string:
preg_grep( "/^". preg_quote($name, '/') . "$/i", $values);
From the documentation:
preg_quote() puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.
Related
I am using the blow code to see if my password contains special char which works fine. but I would like to be able to use a variable like $mySpecialChar instead of the "[\'^£$%&*()}{##~?><>,|=_+¬-]" string, I'm not sure if I can do that. Reason for that is because I want to be able to pull string from a datatable.
I've tried preg_match_all("/".$mySpecialChar."/"), but no luck.
$matches = array();
if (preg_match_all("/[\'^£$%&*()}{##~?><>,|=_+¬-]/", $pwd, $matches) > 0) {
foreach ($matches[0] as $match) { $specialcase += strlen($match); }
}
Make sure to escape any variables you put in a regular expression
preg_match_all('/'.preg_quote($mySpecialChar, '/').'/', $pwd, $matches);
preg_quote
string preg_quote ( string $str [, string $delimiter = NULL ] )
preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.
The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
Note that / is not a special regular expression character.
You have 5 or more special characters in there.
Of note is that last line in the quote above Note that / is not a special regular expression character. While not entirely necessary in your case (I don't see / in your variable string), If you put the second argument as the delimiter it will escape that too. If you pay close attention to what I put above, you will see that is exactly what I did, preg_quote($mySpecialChar, '/')
If you don't quote these, well it's anyone guess what it will do. you could get an error, you could get an empty capture group () you could match anything with the . etc. etc. AS you have it,
[\'^£$%&*()}{##~?><>,|=_+¬-]
This is a character set, so it will escape most of the stuff inside it, that's if that's intentional. If you had [^\'£$%&*()}{##~?><>,|=_+¬-] you would have a not (or negative) character set.
Seeing as you are using preg_match_all, and not preg_match, I can probably assume you don't want the character set. Otherwise why use preg_match_all
It should simply be, if you want to match everything in $mySpecialChar:
preg_match('/['.preg_quote($mySpecialChar, '/').']+', $pwd, $matches);
If you are just trying to match the stuff between the [....], I would still escape it as it doesn't matter, but if you put it in a database and have it start with ^ instead it will make a difference, or if you get the - between certain characters 0-9 for example it may make a difference. Escaping never hurts, just remove the [] when you save it and replace them as I have above.
The [ .... ]+ means 1 or more, the [ ... ]* means none or more. the [...]+
? means one or more non-gready etc. Then you should be able to use just [...]+ with preg_match which will give you a cleaner match then using [...] match one, with preg_match_all.
Most of the time \W (uppercase) will also match most symbols, basically that means [^a-zA-Z0-9_] or not a-Z, 0-9 and _
You could always just look for characters that AREN'T the basic ones:
preg_match_all('/[^0-9A-Za-z]/', $pwd, $matches)
Much shorter and just as effective.
You can easily put this in a string if you like:
$specialChars = '[^0-9A-Za-z]';
preg_match_all("/{$specialChars}/", $pwd, $matches);
Running this on the provided password will return an array in $matches which contains all of the special characters from the string. All you need to do in order to evaluate password complexity is look at the length of $pwd and how many entries are in $matches, as this tells you the number of special characters.
So I have this regex that works on regex101.com
(?:[^\#\\S\\+]*)
It matches the first from first#second.
Whenever I try to use my regex with PHP's preg_replace I don't get the result I expect.
So far I tried it via preg_quote():
\(\?\:\[\^\\#\\S\\\+\]\*\)
And tried it with escaping the original \\ with 4 \'s:
\(\?\:\[\^\\#\\\\S\\\\\+\]\*\)
Still no success. Am I doing something fundamentaly wrong?
I'm just using:
preg_replace("/$regex/", "", $string);
All my other regexes that don't need so many escape chars work perfectly that way.
When you use (?:[^\#\\S\\+]*) in a preg_match in PHP, both in a single or double quoted string literal, the \\S is parsed as a non-whitespace pattern. [^\S] is equal to \s, i.e. it matches whitespace.
The preg_quote() function is only meant to be used to make any string a literal one for a regex, it just escapes all chars that are sepcial regex metacharacters / operators (like (, ), [, etc.), thus you should not use it here.
While you could use a regex to match 1+ chars other than whitespace and # from the start of a string like preg_match('~^[^#\s]+~', $s, $match), you can just explode your input string with # and get the 0th item.
Using :
preg_match_all(
"/\b".$KeyWord."\b/u",
$SearchStr,
$Array1,
PREG_OFFSET_CAPTURE);
This code works fine for all cases except when there is a / in the $KeyWord var. Then I get a warning and unsuccessful match of course.
Any idea how to work around this?
Thanks
use preg_quote() around the keyword.
http://us2.php.net/preg_quote
but also provide your delimiter, so it gets escaped: preg_quote($KeyWord, "/")
You must parse $KeyWord and add "\" before all spec symbols, you can use preg_quote()
Dynamic Values In Patterns
You are using a dynamic value inside the pattern. Like escaping for SQL or HTML, a specific escaping for the value is needed. If you do not escape meta characters inside the value are interpreted by the regex engine. The escaping function for PCRE patterns is preg_quote().
preg_match_all(
"(\b".preg_quote($KeyWord)."\b)u",
$SearchStr,
$Array1,
PREG_OFFSET_CAPTURE
);
Delimiters
The syntax of a pattern in PHPs preg_* function is:
DELIMITER PATTERN DELIMITER OPTIONS
The / is the delimiter in your pattern. So the / inside the $keyWord was recognized as the closing delimiter.
But all non alphanumeric characters can be used. In Perl and JS you can define a regular expression directly (not as string) using / so it is often the default in tutorials.
Most delimiters have to be escaped inside the pattern.
Match a \: '/\//'
The exception to this rule are brackets. You use any of the bracket pairs as delimiter. And because it is a pair, they can still be used inside the pattern.
Match a \: '(/)'
The () brackets are a good decision, you can count them as "subpattern 0".
You can use preg_quote to handle the backslash character.
From the manual:
puts a backslash in front of every
character that is part of the regular
expression syntax
You can also pass the delimiter as the second parameter and it will also be escaped. However, if you're using # as your delimiter, then there's no need to escape /
So, you can either use:
preg_match_all("/\b".preg_quote($KeyWord, "/")."\b/u", $SearchStr,$Array1,PREG_OFFSET_CAPTURE))
or, if you are sure that your keyword does not contain any other regex-special characters, you can simply change the delimiter, and use to escape the backslash:
preg_match_all("#\b".$KeyWord."\b#u", $SearchStr,$Array1,PREG_OFFSET_CAPTURE))
How can i extract https://domain.com/gamer?hid=.115f12756a8641 from the below string ,i.e from url
rrth:'http://www.google.co',cctp:'323',url:'https://domain.com/gamer?hid=.115f12756a8641',rrth:'https://another.com'
P.s :I am new to regular expression, I am learning .But above string seems to be formatted..so some sort of shortcut must be there.
If your input string is called $str:
preg_match('/url:\'(.*?)\'/', $str, $matches);
$url = $matches[1];
(.*?) captures everything between url:' and ' and can later be retrieved with $matches[1].
The ? is particularly important. It makes the repetition ungreedy, otherwise it would consume everything until the very last '.
If your actual input string contains multiple url:'...' section, use preg_match_all instead. $matches[1] will then be an array of all required values.
Simple regex:
preg_match('/url\s*\:\s*\'([^\']+)/i',$theString,$match);
echo $match[1];//should be the url
How it works:
/url\s*\:\s*: matches url + [any number of spaces] + : (colon)+ [any number of spaces]But we don't need this, that's where the second part comes in
\'([^\']+)/i: matches ', then the brackets (()) create a group, that will be stored separately in the $matches array. What will be matches is [^']+: Any character, except for the apostrophe (the [] create a character class, the ^ means: exclude these chars). So this class will match any character up to the point where it reaches the closing/delimiting apostrophe.
/i: in case the string might contain URL:'http://www.foo.bar', I've added that i, which is the case-insensitive flag.
That's about it.Perhaps you could sniff around here to get a better understanding of regex's
note: I've had to escape the single quotes, because the pattern string uses single quotes as delimiters: "/url\s*\:\s*'([^']+)/i" works just as well. If you don't know weather or not you'll be dealing with single or double quotes, you could replace the quotes with another char class:
preg_match('/url\s*\:\s*[\'"]([^\'"]+)/i',$string,$match);
Obviously, in that scenario, you'll have to escape the delimiters you've used for the pattern string...
How do I put a period into a PHP regular expression?
The way it is used in the code is:
echo(preg_match("/\$\d{1,}\./", '$645.', $matches));
But apparently the period in that $645. doesn't get recognized. Requesting tips on how to make this work.
Since . is a special character, you need to escape it to have it literally, so \..
Remember to also escape the escape character if you want to use it in a string. So if you want to write the regular expression foo\.bar in a string declaration, it needs to be "foo\\.bar".
Escape it. The period has a special meaning within a regular expression in that it represents any character — it's a wildcard. To represent and match a literal . it needs to be escaped which is done via the backslash \, i.e., \.
/[0-9]\.[ab]/
Matches a digit, a period, and "a" or "ab", whereas
/[0-9].[ab]/
Matches a digit, any single character1, and "a" or "ab".
Be aware that PHP uses the backslash as an escape character in double-quoted string, too. In these cases you'll need to doubly escape:
$single = '\.';
$double = "\\.";
UPDATE
This echo(preg_match("/\$\d{1,}./", '$645.', $matches)); could be rewritten as echo(preg_match('/\$\d{1,}\./', '$645.', $matches)); or echo(preg_match("/\\$\\d{1,}\\./", '$645.', $matches));. They both work.
1) Not linefeeds, unless configured via the s modifier.