php如何在php字符串中找到exect word

时间:2016-01-20 14:19:29

标签: php string

我想在标题中找到确切的值,这是我的代码

 $title ="Get 25% Off in my title";

    $findme   = array("5% Off","10% off","15% Off","20% Off","25% Off","30% Off","35% Off","40% Off","45% Off","50% Off","55% Off","60% Off","65% Off","70% Off","75% Off","80% Off","$5 Off","$10 Off","$15 Off","$20 Off","$25 Off","$30 Off","$35 Off","$40 Off","$45 Off");

  $array_with_lcvalues = array_map('strtolower',$findme);

    $mystring = strtolower($title);
    foreach($array_with_lcvalues as $match){
       if (strpos($mystring,$match) !== false) {
             echo  $match ;
            } 
        }

我需要知道如何找到确切的值,因为我得到2个值。此代码的确切值应为25%。

代码的输出是 5折优惠 25%的折扣

2 个答案:

答案 0 :(得分:0)

使用正则表达式:

preg_match_all('/(\d+)%\s*off/i', $title, $matches);

继承3v4l代码。

答案 1 :(得分:0)

您可以preg_match使用\b这是一个单词绑定,/i使其不区分大小写。

<?php

$title ="Get 25% Off in my title";

$findme   = array("5% Off","10% off","15% Off","20% Off","25% Off","30% Off","35% Off","40% Off","45% Off","50% Off","55% Off","60% Off","65% Off","70% Off","75% Off","80% Off","$5 Off","$10 Off","$15 Off","$20 Off","$25 Off","$30 Off","$35 Off","$40 Off","$45 Off");

preg_match("/\b(" . implode($findme,"|") . ")\b/i", $title, $matches);

print_r($matches);

?>