【问题标题】:Find exact match with words in php?查找与php中的单词完全匹配?
【发布时间】:2013-03-25 05:26:12
【问题描述】:

我想用锚标记替换可用字符串中的一些单词。但这给我带来了问题。我的做法如下:

$post['Post']['comment'] = 'a class href';
$post['Post']['person'] = 'a';
$post['Post']['place'] = 'class';
$post['Post']['thing'] = 'href';

$thing = "<a class='searchName' href='javascript:void(0)'>".ucfirst($post['Post']['thing'])."</a>";
$person = "<a class='searchName' href='javascript:void(0)'>".ucfirst($post['Post']['person'])."</a>";
$place = "<a class='searchName' href='javascript:void(0)'>".ucfirst($post['Post']['place'])."</a>";

$search_strings = array($person=>$post['Post']['person'],$place=>$post['Post']['place'],$thing=>$post['Post']['thing']);
$kw_to_search_for = $post['Post']['comment'];
foreach($search_strings as $key=>$v)
{               
    if (preg_match('~\b' . $v . '\b~i', $kw_to_search_for, $m))
    {               
        $as[] = str_ireplace($v, $key, $kw_to_search_for);
    } 
}

以上代码的输出为:

Array
(
    [0] => **A** cl**A**ss href
    [1] => a **Class** href
    [2] => a class **Href**
)

但我不想像上面那样输出。根据我的要求,输出应如下所示:

Array
(
    [0] => **A** class href
    [1] => a **Class** href
    [2] => a class **Href**
)

请尽快提出建议.......

【问题讨论】:

  • 为什么不使用 xml 解析器?
  • 此代码示例缺少 $post 值的定义

标签: php regex match cakephp-2.1


【解决方案1】:

如果您使用评论中的空格来分隔单词,它将起作用。

foreach ($search_strings as $key=>$v)
{
    //space at the beginning?
    $a = preg_replace('/\s' . $v . '/i', " $key ", $kw_to_search_for);

    //space at the end?
    $b = preg_replace('/' . $v . '\s/i', " $key ", $kw_to_search_for);

    //if anything replaced, use it
    if ($a !== $kw_to_search_for)
    {
        $as[] = $a;
    }
    elseif ($b !== $kw_to_search_for)
    {
        $as[] = $b;
    }
}

输出有一些额外的空格,但 HTML 应该忽略那很好...

Array
(
    [0] =>  <a class='searchName' href='javascript:void(0)'>A</a> class href
    [1] => a <a class='searchName' href='javascript:void(0)'>Class</a>  href
    [2] => a class <a class='searchName' href='javascript:void(0)'>Href</a>
)

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2020-12-01
    相关资源
    最近更新 更多