2013-03-25 110 views
1

我想用锚标记替换可用字符串中的某些单词。但它给我造成了问题。我在做类似下面:以上代码的在php中查找与单词完全匹配的内容?

$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** 
) 

请尽快与建议.......

+0

为什么不使用XML解析器? – Daedalus 2013-03-25 05:27:36

+0

此代码示例缺少$ post的值的定义 – TML 2013-03-25 05:28:33

回答

0

如果您搜索使用的空间在您的评论来界定它的工作的话。

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> 
) 
相关问题