如何匹配以开头的字符串中的所有空格
How to match all spaces in the string which starts with
我 HTML 有一些文字和标签。例如,
Outer text with [some random text title="My Title Here"], and more text
我想return这个html,但是替换
1. "
无
2.
的所有 空格
从 title=
开始到 ]
。
所以上面 html 的结果将是
Outer text with [some random text title=My Title Here], and more text.
因为我正在使用 PHP 我想使用 preg_replace
但不知道如何构建正确的搜索语句。
我已经实现了类似的东西 (^title=(.+)])
但这只匹配 title="My Title Here"]
- 我需要的是从中减去空格和双引号。
您可以使用 preg_replace_callback
and str_replace
来完成此操作。
echo preg_replace_callback('/(title=)([^\]]+)/', function($match) {
return $match[1] . str_replace(array('"', ' '), array('', ' '), $match[2]);
}, 'Outer text with [some random text title="My Title Here"], and more text');
正则表达式
(title=)([^\]]+)
捕获 title
和 ]
之间的所有内容。更详细的解释见:https://regex101.com/r/cFOYEA/1
它也可以在没有捕获组的情况下完成,https://eval.in/703651(假设起始锚点没有双引号或 space)。
我 HTML 有一些文字和标签。例如,
Outer text with [some random text title="My Title Here"], and more text
我想return这个html,但是替换
1. "
无
2.
从 title=
开始到 ]
。
所以上面 html 的结果将是
Outer text with [some random text title=My Title Here], and more text.
因为我正在使用 PHP 我想使用 preg_replace
但不知道如何构建正确的搜索语句。
我已经实现了类似的东西 (^title=(.+)])
但这只匹配 title="My Title Here"]
- 我需要的是从中减去空格和双引号。
您可以使用 preg_replace_callback
and str_replace
来完成此操作。
echo preg_replace_callback('/(title=)([^\]]+)/', function($match) {
return $match[1] . str_replace(array('"', ' '), array('', ' '), $match[2]);
}, 'Outer text with [some random text title="My Title Here"], and more text');
正则表达式
(title=)([^\]]+)
捕获 title
和 ]
之间的所有内容。更详细的解释见:https://regex101.com/r/cFOYEA/1
它也可以在没有捕获组的情况下完成,https://eval.in/703651(假设起始锚点没有双引号或 space)。