简体   繁体   English

PHP 模式匹配替代数字

[英]PHP pattern matching alternate numbers

How can I count patterns matching [] or [7] in PHP?如何计算 PHP 中匹配 [] 或 [7] 的模式?

I need to match specific patterns in different strings like in the following examples:我需要匹配不同字符串中的特定模式,如下例所示:

Lorem ipsum dolor sit amet, consectetur [] adipiscing elit. Phasellus quis lectus metus, at posuere neque.

and

Lorem ipsum dolor sit amet, consectetur [23] adipiscing elit. Phasellus quis lectus metus, at posuere neque. Sed pharetra nibh [24] eget orci convallis at posuere leo convallis. Sed blandit augue [25] vitae augue scelerisque bibendum. Vivamus sit amet libero turpis, non venenatis urna. In blandit, odio convallis suscipit venenatis, ante ipsum cursus [26] augue.

In the first example, the empty [] will indicate a single point where the pattern needs to be matched and the string replaced.在第一个示例中,空 [] 将指示需要匹配模式和替换字符串的单个点。

The second example has numbers indicating multiple unique points where the strings need to be matched and replaced with unique content.第二个示例的数字指示多个唯一点,其中字符串需要匹配并替换为唯一内容。

I am successfully matching the first example using the following code:我使用以下代码成功匹配了第一个示例:

preg_replace('[]', $replacement, $fulltext);

but, I'm not sure how to match the numbers which are different for other text to be processed.但是,我不确定如何匹配与要处理的其他文本不同的数字。

您的解决方案只是用可选数字进行 preg 替换

preg_replace('/\[\d*\]/', $replacement, $fulltext);

TL;DR; TL; 博士;

You don't need preg_replace for this.为此,您不需要preg_replace Use str_replace instead.请改用str_replace

See below for more detailed explanation.有关更详细的解释,请参见下文。


It's probably important to note that brackets [] have special meaning in PCRE syntax as they indicate character classes .需要注意的是,括号[]PCRE 语法中具有特殊含义,因为它们表示字符类 Which means that your pattern probably isn't doing what you expect it to do here.这意味着您的模式可能没有按照您的预期在此处执行。

For example例如

preg_replace('[]', 'foo', 'Lorem ipsum dolor sit amet, consectetur [] adipiscing elit. Phasellus quis lectus metus, at posuere neque.')

will give you会给你

"fooLfooofoorfooefoomfoo fooifoopfoosfooufoomfoo foodfooofoolfooofoorfoo foosfooifootfoo fooafoomfooefootfoo,foo foocfooofoonfoosfooefoocfootfooefootfooufoorfoo foo[foo]foo fooafoodfooifoopfooifoosfoocfooifoonfoogfoo fooefoolfooifootfoo.foo fooPfoohfooafoosfooefoolfoolfooufoosfoo fooqfooufooifoosfoo foolfooefoocfootfooufoosfoo foomfooefootfooufoosfoo,foo fooafootfoo foopfooofoosfooufooefoorfooefoo foonfooefooqfooufooefoo.foo"

which is not likely what you want at all.这根本不是你想要的。

This is because PCRE also requires delimiters enclosing the pattern.这是因为 PCRE 还需要包含模式的分隔符 Here the brackets will be treated as delimiters and you end up with an empty pattern.这里括号将被视为分隔符,最终得到一个空模式。

It is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively.也可以使用括号样式分隔符,其中开始和结束括号分别是开始和结束分隔符。 () , {} , [] and <> are all valid bracket style delimiter pairs. (){}[]<>都是有效的括号样式分隔符对。

Instead you should use相反,你应该使用

preg_replace('/\[\d*\]/', $replacement, $fulltext);

This escapes the brackets with the \\ backslash character for literals and provides an optional number of digit characters to fall within the pattern matching expression.这将用\\反斜杠字符转义括号,并提供可选数量的数字字符以落入模式匹配表达式。

If you wish for the replacement string to fall within the brackets themselves and not replace the actual brackets you can enclose the pattern in round braces and use back references to do the replacement.如果您希望替换字符串位于括号内而不替换实际括号内,您可以将模式括在圆括号中并使用反向引用进行替换。

If you want to match specific patterns to specific replacement strings ( where the pattern is more complex than just a simple substring search/replace ) then you should use preg_replace_callback_array instead.如果要将特定模式与特定替换字符串匹配(其中模式比简单的子字符串搜索/替换更复杂),则应改用preg_replace_callback_array However, it's important to note that this function is only available in PHP 7但是,需要注意的是,此功能仅在 PHP 7 中可用

Example例子

$newText = preg_replace_callback_array(
               [
                   '/\[(23)\]/' => function ($match) {
                       return 'foo';
                   },
                   '/\[(24)\]/' => function ($match) {
                       return 'bar';
                   },
               ],
               $fulltext
           );

Which would give you something like...这会给你类似的东西......

"Lorem ipsum dolor sit amet, consectetur foo adipiscing elit. Phasellus quis lectus metus, at posuere neque. Sed pharetra nibh bar eget orci convallis at posuere leo convallis. Sed blandit augue [25] vitae augue scelerisque bibendum. Vivamus sit amet libero turpis, non venenatis urna. In blandit, odio convallis suscipit venenatis, ante ipsum cursus [26] augue."

If what you really need is to do replacement based on substring search (such that [23] will be replaced with the string 'foo' and [24] will be replaced with the string 'bar', etc...) then you don't need a regular expression.如果您真正需要的是基于子字符串搜索进行替换(例如 [23] 将被替换为字符串 'foo' 并且 [24] 将被替换为字符串 'bar' 等...),那么您不需要不需要正则表达式。 Instead you can use str_replace for this.相反,您可以为此使用str_replace

Here's an example...这是一个例子...

$fulltext = 'Lorem ipsum dolor sit amet, consectetur [23] adipiscing elit. Phasellus quis lectus metus, at posuere neque. Sed pharetra nibh [24] eget orci convallis at posuere leo convallis. Sed blandit augue [25] vitae augue scelerisque bibendum. Vivamus sit amet libero turpis, non venenatis urna. In blandit, odio convallis suscipit venenatis, ante ipsum cursus [26] augue.';
$searchStrings = [
                  '[23]',
                  '[24]',
                  '[25]',
                  '[26]',
                 ];
$replacements  = [
                  '[foo]',
                  '[bar]',
                  '[baz]',
                  '[quix]',
                 ];
$newText = str_replace($searchStrings, $replacements, $fulltext);

Which gives you这给你

"Lorem ipsum dolor sit amet, consectetur [foo] adipiscing elit. Phasellus quis lectus metus, at posuere neque. Sed pharetra nibh [bar] eget orci convallis at posuere leo convallis. Sed blandit augue [baz] vitae augue scelerisque bibendum. Vivamus sit amet libero turpis, non venenatis urna. In blandit, odio convallis suscipit venenatis, ante ipsum cursus [quix] augue."

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM