Page 1 of 1
Starting and ending the expression with special character
Posted: Tue Jan 12, 2010 8:07 am
by LDusan
Since '/' or '#' or other special characters are used to delimit regular expression, how could I write expression in which the expression itself starts and end with special characters. For example:
Code: Select all
preg_match_all ('/!.*?.!/',$val5,$out2);
This won't work, I guess because '!' is taken as delimiter instead of '/'. Any ideas?
Re: Starting and ending the expression with special character
Posted: Tue Jan 12, 2010 11:05 am
by AbraCadaver
Depends upon what you're trying to match. I don't think you need to escape the exclamations marks.
Re: Starting and ending the expression with special character
Posted: Tue Jan 12, 2010 11:51 am
by LDusan
I am trying to match everything that starts and ends with "!" and put it in array using preg_match_all.
Re: Starting and ending the expression with special character
Posted: Tue Jan 12, 2010 11:54 am
by pickle
The regex engine uses the first character - so the ! is not being treated as a delimiter in this case. I think you just have your expression wrong.
Re: Starting and ending the expression with special character
Posted: Mon Jan 25, 2010 11:41 am
by ridgerunner
LDusan wrote:Since '/' or '#' or other special characters are used to delimit regular expression, how could I write expression in which the expression itself starts and end with special characters. For example:
Code: Select all
preg_match_all ('/!.*?.!/',$val5,$out2);
This won't work, I guess because '!' is taken as delimiter instead of '/'. Any ideas?
Actually, in your regex the '!' is not the delimiter, the matching '/' chars are the delimiters. The only error with your regex is the extra dot right before the second '!' which matches any char in this position (which you don't want). Remove the second dot and your regex works just fine.
But using the lazy dot-star is not the best solution for this problem. Better is to specifically match exactly what you want (non-'!'s). Since you are looking for a string of characters that are not '!', say exactly that in the regex by using '[^!]*' rather than '.*?' like so:
Code: Select all
$count = preg_match_all ('/![^!]*!/', $subject, $matches);
Hope this helps!
