douliaotong4944 2016-09-02 05:33
浏览 74
已采纳

preg_match_all不匹配所有可能性

I'm trying to retrieve all matches however I am only receiving one

Here is my string

$html = '<p> This is my Home Page.</p><p><span style="line-height: 1.42857;">{{ type="slider" }} </span></p><p> </p>';

If you see string contain {{ type="slider" }} , now if i write this string only once i am getting my expected result, but if i write it multiple times in html sting like {{ type="slider" }} {{ type="banned" }} {{ type="testimonial" }}

$html = '<p> This is my Home Page.</p><p><span style="line-height: 1.42857;">{{ type="slider" }} {{ type="banner" }} {{ type="testimonial" }}  </span></p><p> </p>';

and try to get the values within my string {{ type=" ???? " }} it shows weird result

I am using this below code .

preg_match_all('/{{ type=\"(.+)\" }}/', $html, $matches, PREG_SET_ORDER);
echo "<pre>";
print_r($matches);
foreach ($matches as $val) {
    echo "matched: ". $val[0] . "<br/>";
    echo "My Value" . $val[1] . "<br/>"; 
}

Current Result :

Array
(
    [0] => Array
        (
            [0] => {{ type="slider" }} {{ type="banner" }} {{ type="testimonial" }}
            [1] => slider" }} {{ type="banner" }} {{ type="testimonial
        )

)
matched: {{ type="slider" }} {{ type="banner" }} {{ type="testimonial" }}
My Value : slider" }} {{ type="banner" }} {{ type="testimonial

I am expecting result in array with the values written between {{ type=" and " }}

with {{ type="slider" }} only i am getting this result which is perfect.

Array
(
    [0] => Array
        (
            [0] => {{ type="slider" }}
            [1] => slider
        )

)
matched: {{ type="slider" }}
My Value : slider

Any idea ?

Sorry for my bad english.

  • 写回答

2条回答 默认 最新

  • doumi4676 2016-09-02 05:42
    关注

    You need to make your regex match non-greedy by adding either a ? :

    preg_match_all('/{{ type=\"(.+?)\" }}/', $html, $matches, PREG_SET_ORDER);
    

    or the U modifier:

    preg_match_all('/{{ type=\"(.+)\" }}/U', $html, $matches, PREG_SET_ORDER);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败