how to use regex special characters in pattern in preg_replace

若如初见. 提交于 2021-02-05 08:09:47

问题


I am trying to replace 2.0 to stack,

but the following code replace 2008 to 2.08

Following is my code:

$string = 'The story is inspired by the Operation Batla House that took place in 2008 ';
$tag = '2.0';
$pattern = '/(\s|^)'.($tag).'(?=[^a-z^A-Z])/i';
echo preg_replace($pattern, '2.0', $string);

回答1:


Use preg_quote and make sure you pass the regex delimiter as the second argument:

$string = 'The story is inspired by the Operation Batla House that took place in 2008 ';
$tag = '2.0';
$pattern = '/(\s|^)' . preg_quote($tag, '/') . '(?=[^a-zA-Z])/i';
//                     ^^^^^^^^^^^^^^^^^^^^^
echo preg_replace($pattern, '2.0', $string);

The string is not modified. See the PHP demo. The regex delimiter here is /, thus it is passed as the 2nd parameter to preg_quote.

Note that [^a-z^A-Z] matches any chars but ASCII letters and ^ since you added the second ^ in the character class. I changed [^a-z^A-Z] to [^a-zA-Z].

Also, the capturing group at the start may be replaced with a single lookbehind, (?<!\S), it will make sure your match occurs only at the string start or after a whitespace.

If you expect to also match at the end of the string, replace (?=[^a-zA-Z]) (that requires a char other than a letter immediately to the right of the current location) with (?![a-zA-Z]) (that requires a char other than a letter or end of string immediately to the right of the current location).

So, use

$pattern = '/(?<!\S)' . preg_quote($tag, '/') . '(?![a-zA-Z])/i';

Also, consider using unambiguous word boundaries

$pattern = '/(?<!\w)' . preg_quote($tag, '/') . '(?!\w)/i';


来源:https://stackoverflow.com/questions/57019521/how-to-use-regex-special-characters-in-pattern-in-preg-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!