【问题标题】:How to apply this regex? in php如何应用这个正则表达式?在php中
【发布时间】:2017-06-20 18:08:47
【问题描述】:

如何应用这个正则表达式?在 PHP 中 我有代码

$a = "{temp}name_temp1{/temp}  Any thing Any thing {temp}name_temp2{/temp}";

我只需要 name_temp1name_temp2

{temp}This{/temp}

中的任何名称

谢谢你

【问题讨论】:

标签: php html regex


【解决方案1】:

你可以使用惰性量词:

{temp}         # look for {temp}
(?P<value>.+?) # anything else afterwards
{/temp}        # look for {/temp}


PHP 中,这将是:
<?php

$a = "{temp}name_temp1{/temp}  Any thing Any thing {temp}name_temp2{/temp}";

$regex = '~{temp}(?P<value>.+?){/temp}~';
preg_match_all($regex, $a, $matches, PREG_SET_ORDER);

foreach($matches as $match) {
    echo $match["value"];
}
?>

【讨论】:

  • 这里\Q...\E序列的目的是什么?
  • 为什么花括号不表示特殊含义!?
  • 你做到了,但还需要修改初始描述。
  • 感谢您的回复
【解决方案2】:

试试这个正则表达式:{temp}(.*?){\/temp}

你可以像这样在 PHP 中使用它:

$a = "{temp}name_temp1{/temp}  Any thing Any thing {temp}name_temp2{/temp}";

preg_match_all('/{temp}(.*?){\/temp}/', $a, $matches);

var_dump($matches[1]); // Returns ['name_temp1', 'name_temp2']

eval.in demo

【讨论】:

  • 感谢您的回复
猜你喜欢
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
  • 2011-02-05
相关资源
最近更新 更多