php 用可选的括号替换单词
php replace a word with optional parentheses
我只想删除下面字符串中的最后一个 "world"
。
我也想要匹配括号。它应该是可选的。
例如两者:
$string = 'this is my world, not my (world)';
$string = 'this is my world, not my world';
结果应该是 this is my world, not my
代码:
$string = 'this is my world, not my (world)';
$find = 'world';
$replace = '';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result);
您可以通过交替进行正则表达式替换:
$input = 'this is my world, not my (world)';
$output = preg_replace("/(?:\(world\)|\bworld\b)(?!.*\bworld\b)/", "", $input);
echo $input . "\n" . $output;
这会打印:
this is my world, not my (world)
this is my world, not my
下面是对正则表达式模式的解释:
(?: match (but do not capture)
\(world\) either (world)
| OR
\bworld\b world
)
(?!.*\bworld\b) assert that no other occurrence of world or (world) occurs
later in the string
在 PHP (PCRE) 中你可以使用这个 conditional regex construct:
(.*)\h+(\()?world(?(2)\)|\b)
并替换为:
正则表达式详细信息:
(.*)
:在开始时匹配 0 个或多个字符(贪婪或最长的可能匹配)并将其捕获到组 #1
\h+
: 匹配1个或多个水平空格
(\()?
:可选 匹配开局 (
并将其捕获到第 2 组
world
:匹配文本world
(?(2)\)|\b)
:如果捕获组 2 存在则匹配 )
否则匹配单词边界
PHP代码:
$repl = preg_replace('/(.*)\h+(\()?world(?(2)\)|\b)/', '', $str);
我只想删除下面字符串中的最后一个 "world"
。
我也想要匹配括号。它应该是可选的。
例如两者:
$string = 'this is my world, not my (world)';
$string = 'this is my world, not my world';
结果应该是 this is my world, not my
代码:
$string = 'this is my world, not my (world)';
$find = 'world';
$replace = '';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result);
您可以通过交替进行正则表达式替换:
$input = 'this is my world, not my (world)';
$output = preg_replace("/(?:\(world\)|\bworld\b)(?!.*\bworld\b)/", "", $input);
echo $input . "\n" . $output;
这会打印:
this is my world, not my (world)
this is my world, not my
下面是对正则表达式模式的解释:
(?: match (but do not capture)
\(world\) either (world)
| OR
\bworld\b world
)
(?!.*\bworld\b) assert that no other occurrence of world or (world) occurs
later in the string
在 PHP (PCRE) 中你可以使用这个 conditional regex construct:
(.*)\h+(\()?world(?(2)\)|\b)
并替换为:
正则表达式详细信息:
(.*)
:在开始时匹配 0 个或多个字符(贪婪或最长的可能匹配)并将其捕获到组 #1\h+
: 匹配1个或多个水平空格(\()?
:可选 匹配开局(
并将其捕获到第 2 组world
:匹配文本world
(?(2)\)|\b)
:如果捕获组 2 存在则匹配)
否则匹配单词边界
PHP代码:
$repl = preg_replace('/(.*)\h+(\()?world(?(2)\)|\b)/', '', $str);