<?php
function pregForPreg($value)
{
$value = preg_replace(array('#\(#', '#\)#', '#\+#', '#\?#', '#\*#', '#\##', '#\[#', '#\]#', '#\&#', '#\/#', '#\$#', '#\\\\#'), array('\(', '\)', '\+', '\?', '\*', '\#', '\[', '\]', '\&', '\/', '\\\$', '\\\\'), $value);
return $value;
}
$var = "TI - Yeah U Know [OFFCIAL VIDEO] [TAKERS] [w\LYRICS]";
$var = pregForPreg($var);
//$var is now:
// TI - Yeah U Know \[OFFCIAL VIDEO\] \[TAKERS\] \[w\LYRICS\]
$var = preg_replace("#" . $var . "#isU", 'test', $var);
echo $var;
And I get an error: *Warning: preg_replace(): Compilation failed: PCRE does not support \L, \l, \N, \U, or \u at offset 50 in test.php on line 13.*
How to make a correct function pregForPreg?
It seems you want to escape special regex characters. This function already exists and is called
preg_quote().You get the error, because you don’t escape
\properly:and
\Lhas special meaning in Perl regular expression:but is not supported in PHP’s PCRE (Perl Differences):
Update:
Obviously, you cannot use the escaped version as value and as pattern, because in the pattern
\[will be treated as[and but in the value\[is taken literally. You have to store the escaped string in a new variable:or easier:
Side note: If you really wanted to match
\[in a string, the regular expression would be\\\\\[. You see, it can get quite ugly.