【问题标题】:str_replace with whole words onlystr_replace 仅用整个单词
【发布时间】:2014-10-20 04:45:17
【问题描述】:

我正在尝试获取一个字符串,删除一个单词列表和任何数字,然后在 MySQL 查询中使用结果。

它会回显出我要隔离的单词,但是当我将该单词与字符串相等时,它会返回 false 并且不会查询。

$remove_odonyms=preg_replace("/\b(st|street|rd|road|ln|lane|ter|terrace|ave|avenue|blvd|boulevard|ct|court)\b/", "", $search);

function remove_numbers($string) {
$num = array(1,2,3,4,5,6,7,8,9,0);
return str_replace($num, '', $string);
}
$street_only=remove_numbers($remove_odonyms);

所以对于字符串 $search="60 main street" echo $remove_odonyms"60 main"echo $street_only"main"

但他们不会查询,也不会查询

if($street_only="main"){ echo "true";}

编辑:我正在做的查询是

$query="
SELECT * FROM column WHERE number='$int' AND odonym='$odonym' AND street_name='$street_only'
";

它什么也不返回。但是当我将其更改为street_name="main" 时,它会返回我要查找的结果。

【问题讨论】:

  • 你有什么错误吗?看起来工作代码
  • 你想要的输出和你得到的并不清楚。您能否进行编辑以更清楚地了解正在发生或未发生的事情?

标签: php mysql regex preg-replace


【解决方案1】:

您有一个额外的空间,因此您需要修剪以删除空间。所以在查询之前使用 trim() 删除空格并匹配查询中的确切单词。

$street_only = trim($street_only);

【讨论】:

    【解决方案2】:

    你要为 sql 注入敞开心扉,顺便说一句....正如你所看到的,有很多方法可以做到这一点..

    <?php
    
    $str = '120 taco bell bvld. 123';  
    
    $str = preg_replace('/[^a-zA-z ]/','',$str);
    $str = str_ireplace(array('street','road','rd','ct','court','bvld'),'',$str); 
    $str = trim($str); 
    
    $arr = preg_split('/\s/',$str);
    
    $just_street = join(' ',$arr);
    
    print $just_street; 
    
    ?>
    

    【讨论】:

      【解决方案3】:
      $textString ="tim timtim lovetim hitim wholetim byetimbye";
      $text = preg_replace('/\btim\b/', 'pankaj', $textString);
      echo $text; 
      

      【讨论】:

        【解决方案4】:

        如果你想过滤更多,你可以做几件事:

        // Case sensitive string (you may or may not have a upper/lower, but the function is here to see both...)
        $search         =   '16 Main Street';
        // added case insensitive on the chance there are uppers
        $remove_odonyms =   preg_replace("/\b(st|street|rd|road|ln|lane|ter|terrace|ave|avenue|blvd|boulevard|ct|court)\b/i", "", $search);
        
        function remove_numbers($string) {
                // remove all numbers
                return trim(preg_replace('/[0-9]/','',$string));
            }
        // Presumming you are storing all lower, force lowercase
        // This will echo "main"
        $street_only    =   strtolower(remove_numbers($remove_odonyms));
        

        【讨论】:

          猜你喜欢
          • 2012-03-29
          • 2016-08-24
          • 1970-01-01
          • 2012-09-21
          • 2019-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-11
          相关资源
          最近更新 更多