Re: Help on pregreplace
| From: | Tom Worster | Date: | Tue, 18 Aug 2009 15:12:03 +0000 |
| Subject: | Re: Help on pregreplace | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-296927@lists.php.net to get a copy of this message | ||
On 8/18/09 10:56 AM, "Merlin Morgenstern" <merlin_x@fastmail.fm> wrote:
>
>
> Ashley Sheridan wrote:
>> On Tue, 2009-08-18 at 16:00 +0200, Merlin Morgenstern wrote:
>>> Hi there,
>>>
>>> I am highlighting keywords with the help of pregreplace. This works
>>> great with one limitation. If the word that has to be replaced contains
>>> a slash, preg throws an error. So far I could not find a fix. Can
>>> someone help?
>>>
>>> Here is the code:
>>>
>>>
>>> $pattern = "/\b($words)\b/is";
>>> $replace = '<span
>>> style="background:#FF0000;color:#FCCCCC;">\\1</span>';
>>> return preg_replace($pattern,$replace,$str);
>>>
>>> Thank you in advance,
>>>
>>> Merlin
>>>
>> Well, a slash has a special meaning inside PHP strings, more so for
>> double quoted strings. Are you correctly escaping the slash as a double
>> slash so that it's not interpreted by the string as an escaped
>> character, as you will need to as the preg_replace will be interpreting
>> it as an escape sequence to match?
>>
>> Thanks,
>> Ash
>> http://www.ashleysheridan.co.uk
>>
>>
>>
> HI, replacing the delimiter slash by ~ solved the problem. Thank you
which means that words with ~ in them will fail. as Al pointed out,
preg_quote() is a more general solution. it escapes all tricky pcre
characters as well as the delimiter.