【问题标题】:Regular expression, any string between two strings with multiple occurences正则表达式,两个字符串之间多次出现的任意字符串
【发布时间】:2012-07-25 18:38:16
【问题描述】:

我在 PHP 中使用一个简单的正则表达式来解析自定义模板

$row = preg_replace_callback(
    '/\^([^\^]+)\^/', create_function ('$m', 'global $fields_ar; return $fields_ar{$m[1]};'),
    $template
    );

基本上,两个 ^ 之间的所有内容都替换为相应的变量名称值,例如如果 $template 是:

 <td>^title_source^ by ^author_source^<br/>

$fields_ar['title_source'] == 'my title' and  $fields_ar['author_source'] == 'my author'

$row 变为:

<td>my title by my author<br/>

一切正常,但我想更改分隔符;而不是 ^,它有可能包含在其他两个 ^ 之间,我想使用一个字符串,例如然而,“sel3ction”:

$row = preg_replace_callback(
    '/sel3ction([^sel3ction]+)sel3ction/', create_function ('$m', 'global $fields_ar; return $fields_ar{$m[1]};'),
    $template
    );

不起作用;我很确定问题出在消极方面。

有什么建议吗?

我知道这不是一种“干净”的方法,因为即使是最奇怪的字符串也可能很棘手,但目前我想尝试使用这种方法。如果您有更标准的解决方案,当然欢迎。

谢谢!

【问题讨论】:

标签: php regex templates


【解决方案1】:

您可以使用惰性量词 (?) 告诉您的表达式在匹配 . 时不要贪婪:

/sel3ction(.+?)sel3ction/

这告诉正则表达式引擎不要将.(在本例中为“sel3ction”)之后的内容与其他可能匹配的内容匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2014-12-08
    • 2014-06-12
    • 2012-05-30
    相关资源
    最近更新 更多