You have made 3 errors but your pattern doesn't work for only one reason.
How to write a literal string in a pattern?
?
is a special character in a regex and means optional (after a character) or turn a quantifier to lazy (after +
, *
, ?
, {n,m}
) or is part of syntax for several features (non capturing or atomic groups, conditionals, recursion, definitions).
If you want to write it as literal in a pattern, you must escape it:
php?profil => php\?profil
This is the only reason your pattern doesn't work.
The same with a literal dot. .
has a special meaning and must be escaped:
index.php => index\.php
But since .
means all characters, it matches the literal dot too.
There are twelve special characters that must be escaped in a pattern to be used as literal:
[ ( ) { ? * + ^ $ \ | .
Note that when the opening curly bracket {
is not followed by something like this: 2,5}
or ,5}
or 2,}
, the situation isn't ambiguous (i.e. the opening curly bracket is not the begining of a {n,m}
quantifier.) and you don't need to escape it.
However an other character must be escaped: the pattern delimiter.
With PHP you must use a pattern delimiter to enclose a pattern, the most used is the slash /
but you can use an other character like ~
#
@
... (note that using a regex special character or a character that is used as literal many times in the pattern is a bad idea.)
You seems to have forgotten to put the delimiters since the @
are part of the original string. In the pattern, the @
is seen as a delimiter because it is the first character, but it is not seen as a literal @
. If you want to match the @
you must enclose your pattern with delimiters.
So, the correct pattern is :
$search = '/@<a class="uye" href="index\.php\?profil=(.*?)" contenteditable="false">@/';
If you want to avoid to search and escape each special character in a literal string, you can enclose your literal string between \Q....\E
:
$search = '/\Q@<a class="uye" href="index.php?profil=\E(.*?)\Q" contenteditable="false">@\E/';
(the pattern delimiter (if present), must always be escaped.)
Or you can use the preg_quote()
function:
$search = '/' . preg_quote('@<a class="uye" href="index.php?profil=', '/') . '(.*?)' . preg_quote('" contenteditable="false">@', '/') .'/';
The second (optional) argument of preg_quote()
is the delimiter. I have written it, but it is /
by default.