如何只用数字替换字符串结尾 - preg_replace php

How to replace only string end with number - preg_replace php

这是我的字符串。

$text = 'I am  [pitch = "high"]Rudratosh Shastri[endpitch]. what is your name ? how  are you? sorry [pause ="3000"] i can not hear you ?[rate="-70.00%"] i still can\'t hear you[endrate] ? [rate="+50.00%"]why i can\'t hear you[endrate] ?';

我想用<break time="3000ms">

替换[pause = "3000"]

我写了下面的正则表达式,但它一直选择到最后 "]

\[pause.*\"(\d+)\".*\"]

PHP : $text = preg_replace("/\[pause.*\"(\w+)\".*\"]/", '<break time="ms"/>', $text);

如果我要找到正则表达式只选择 'any number'

的解决方案
any number"]

我的问题就解决了。

但是我找不到怎么做。

你有什么建议吗?

您可以使用

\[pause[^]]*"(\d+)"]

或者(如果数字后面可能还有别的东西):

\[pause[^]]*"(\d+)"[^]]*]
                   ^^^^^

并替换为 <break time="ms"/>。请参阅 regex demo

详情

  • \[pause - [pause 子字符串
  • [^]]* - ]
  • 以外的 0+ 个字符
  • " - 双引号
  • (\d+) - 第 1 组:一个或多个数字
  • "] - "] 子串。

PHP demo:

$str = 'I am  [pitch = "high"]Rudratosh Shastri[endpitch]. what is your name ? how  are you? sorry [pause ="3000"] i can not hear you ?[rate="-70.00%"] i still can\'t hear you[endrate] ? [rate="+50.00%"]why i can\'t hear you[endrate] ?';
echo preg_replace('~\[pause[^]]*"(\d+)"]~', '<break time="ms"/>', $str);
// => I am  [pitch = "high"]Rudratosh Shastri[endpitch]. what is your name ? how  are you? sorry <break time="3000ms"/> i can not hear you ?[rate="-70.00%"] i still can't hear you[endrate] ? [rate="+50.00%"]why i can't hear you[endrate] ?

由于最后一部分 .*\",您的正则表达式匹配太多 .*\" 如果您删除该部分,您将匹配当前示例数据,但第一个 .* 仍然匹配任何字符,包括 for例如 "[] 这样的字符。

你可以做的是通过匹配水平空白字符包围的等号来替换第一个 .*,例如 \h*=\h*

请注意,您不必转义双引号。

您可能会使用:

\[pause\h*=\h*"(\d+)"]

Regex demo

那将匹配

  • \[pause 匹配 [pause
  • \h* 匹配零个或多个水平空白字符
  • =匹配=
  • \h*" 匹配零个或多个水平空白字符后跟 "
  • (\d+)在一组中捕获一个或多个数字
  • "] 匹配 "]

并替换为:

<break time="ms"> 或使用 <break time="ms"/>

例如:

$text = 'I am  [pitch = "high"]Rudratosh Shastri[endpitch]. what is your name ? how  are you? sorry [pause ="3000"] i can not hear you ?[rate="-70.00%"] i still can\'t hear you[endrate] ? [rate="+50.00%"]why i can\'t hear you[endrate] ?';
$text = preg_replace('/\[pause\h*=\h*"(\d+)"]/', '<break time="ms"/>', $text);
echo $text;

Demo