如何匹配以字符串开头的所有空格

时间:2022-02-04 16:49:50

I have HTML with some text and tags. For example,

我有一些带有文字和标签的HTML。例如,

Outer text with [some random text title="My Title Here"], and more text

I would like to return this html, but replace
1. " for nothing
2. all spaces for  

我想返回这个HTML,但是替换1.“没有任何东西2.所有空间为 

From the START of title= till ].

从标题的开头=到]。

So that result of above html will be

所以上面的html的结果将是

Outer text with [some random text title=My Title Here], and more text.

As I'm using PHP I'd like though to use preg_replace but no idea how to construct corectly search statement.

因为我正在使用PHP,我想使用preg_replace但不知道如何构建corectly搜索语句。

I've achieved something like this (^title=(.+)]) but this only matches title="My Title Here"] - what I need is to subtract from it spaces and double quotes.

我已经实现了类似的东西(^ title =(。+)])但这只匹配title =“我的标题在这里”] - 我需要的是从空格和双引号中减去它。

1 个解决方案

#1


2  

You can use preg_replace_callback and str_replace to accomplish this.

您可以使用preg_replace_callback和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');

The regex

(title=)([^\]]+)

captures everything between title and a ]. For a more detailed explanation see: https://regex101.com/r/cFOYEA/1

捕获标题和a之间的所有内容。有关更详细的说明,请参阅:https://regex101.com/r/cFOYEA/1

Demo: https://eval.in/703649

It also can be done without the capture groups, https://eval.in/703651 (assuming the starting anchor wont have a double quote or space in it).

它也可以在没有捕获组的情况下完成,https://eval.in/703651(假设起始锚不会有双引号或空格)。

#1


2  

You can use preg_replace_callback and str_replace to accomplish this.

您可以使用preg_replace_callback和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');

The regex

(title=)([^\]]+)

captures everything between title and a ]. For a more detailed explanation see: https://regex101.com/r/cFOYEA/1

捕获标题和a之间的所有内容。有关更详细的说明,请参阅:https://regex101.com/r/cFOYEA/1

Demo: https://eval.in/703649

It also can be done without the capture groups, https://eval.in/703651 (assuming the starting anchor wont have a double quote or space in it).

它也可以在没有捕获组的情况下完成,https://eval.in/703651(假设起始锚不会有双引号或空格)。