Php 如何替换字符串中出现的所有$关键字,而不替换URL和图像标记中的关键字?

Php 如何替换字符串中出现的所有$关键字,而不替换URL和图像标记中的关键字?,php,replace,Php,Replace,如何替换字符串中出现的所有关键字,而不替换超链接URL、图像标记URL、图像标记标题和alt标记中的关键字 例如: $keywords = 'sports'; $string = '<a href="http://my_domain_name.com/sports/info.php"><img class="icon" src="http://my_domain_name.com/sports/images/football.gif" title="Get the lates

如何替换字符串中出现的所有关键字,而不替换超链接URL、图像标记URL、图像标记标题和alt标记中的关键字

例如:

$keywords = 'sports';

$string = '<a href="http://my_domain_name.com/sports/info.php"><img class="icon" src="http://my_domain_name.com/sports/images/football.gif" title="Get the latest football sports news" alt="Get the latest football sports news" />Football sports news</a>';
$keywords='sports';
$string='';
请注意,关键字“sports”与超链接URL、图像标记URL、图像标记标题和alt标记一起出现

我想将$keywords(运动)替换为:

运动
要获得以下结果:

<a href="http://my_domain_name.com/sports/info.php"><img class="icon" src="http://my_domain_name.com/sports/images/football.gif" title="Get the latest football sports news" alt="Get the latest football sports news" />Football <span style="color: #000000; background-color: #FFFF00; font-weight: normal;">sports</span> news</a>

提前谢谢

编辑-其他信息

目前我正在使用以下两步方法,它只适用于URL,而不适用于标题和alt标记。我还需要not替换title和alt标签中的关键字

// Replaces both the website and general images path urls with character strings (used to prevent highlighting keywords found within the path urls)
   if(strpos('http://my_domain_name.com/sports', $keywords) != false) {
     $description = str_ireplace('http://my_domain_name.com/sports', '1q2w3e4r5t6y7u', $description);
   }
   if(strpos('http://my_domain_name.com/sports/images', $keywords) != false) {
     $description = str_ireplace('http://my_domain_name.com/sports/images', '7u6y5t4r3e2w1q', $description);
   }

// Highlights the Search Keywords
   $description = str_ireplace($keywords, '<span style="color: #000000; background-color: #FFFF00; font-weight: normal;">'.$keywords.'</span>', $description);

// Replaces the character strings with the website and general images path urls
   if(strpos('http://my_domain_name.com/sports', $keywords) != false) {
     $description = str_ireplace('1q2w3e4r5t6y7u', 'http://my_domain_name.com/sports', $description);
   }
   if(strpos('http://my_domain_name.com/sports/images', $keywords) != false) {
     $description = str_ireplace('7u6y5t4r3e2w1q', 'http://my_domain_name.com/sports/images', $description);
   }
//用字符串替换网站和常规图像路径URL(用于防止突出显示路径URL中的关键字)
如果(STRPO('http://my_domain_name.com/sports“,$keywords)!=false){
$description=str_ireplace('http://my_domain_name.com/sports“,”1q2w3e4r5t6y7u“,$说明);
}
如果(STRPO('http://my_domain_name.com/sports/images“,$keywords)!=false){
$description=str_ireplace('http://my_domain_name.com/sports/images“,”7u6y5t4r3e2w1q“,$说明);
}
//突出显示搜索关键字
$description=str_ireplace($keywords、.$keywords.'、$description);
//将字符串替换为网站和常规图像路径URL
如果(STRPO('http://my_domain_name.com/sports“,$keywords)!=false){
$description=str_ireplace('1q2w3e4r5t6y7u','http://my_domain_name.com/sports“,$说明);
}
如果(STRPO('http://my_domain_name.com/sports/images“,$keywords)!=false){
$description=str_ireplace('7u6y5t4r3e2w1q','http://my_domain_name.com/sports/images“,$说明);
}

xml\u parse可用于去除HTML代码中的标记。 这是一个关于如何使用它的好教程

我会从字符串中去掉所有html标记,然后使用:
str\u replace($keyword,$replace\u string,$string)

做剩下的事


$replace_string=“{$keywords}”;
$string='';
$exploded=exploded(“”+1)//得到标签的末尾
$tmp_string=substr($abit,$pos);
如果(strlen($tmp_string)>1){//在标记之外有文本
$tmp\u string=str\u ireplace($keywords、$replace\u string、$tmp\u string);
$tmp_数组[]=substr($abit,0,$pos)。$tmp_字符串;
}否则{
$tmp_数组[]=$abit;
}
}

$newstring=infrade(这是我使用PHP的

$str='';
$doc=新的DOMDocument();
$fragment=$doc->createDocumentFragment();
$fragment->appendXML($str);
$doc->appendChild($fragment);
//创建
$node=$doc->createElement('span');
$node->setAttribute('style','color:#000000;背景色:#FFFF00;字体重量:normal;');
$node->nodeValue='sports';
foreach($doc->getElementsByTagName('a')作为$tag)
{
$img_tag=$tag->firstChild->cloneNode();
$text=$doc->createTextNode($tag->textContent);
$tag->nodeValue='';//清除


(您需要PHP>5.3)

仅处理字符串我将执行以下操作,因为所有属性值始终位于元素值之前。很容易找到正确的匹配项,然后使用回调函数以任意方式替换“sports”

也许你需要的更多:

function replacer($match)
{
    global $replace_match_with_this, $string_to_replace;
    return str_ireplace($string_to_replace, $replace_match_with_this, $match[0]);
}

$new_string = preg_replace_callback(sprintf('/>[^<>]*[\s-]+%s[\s-]+[^<>]*<\/a>/i', $keyword), 'replacer', $string, 1);
函数替换程序($match)
{
全局$replace\u将\u与\u匹配此$string\u与\u replace;
返回str_ireplace($string_to_replace,$replace_match_with_this,$match[0]);
}
$new_string=preg_replace_回调(sprintf('/>[^]*[\s-]+%s[\s-]+[^]*/i',$keyword),'replacer',$string,1);

大概$keyword和$string\u to\u replace具有相同的值,可以组合成一个变量。

可能是@CodeCaster的重复我遗漏了什么吗?问题中的正则表达式在哪里?@PeeHaa那么你不明白我的意思。这里需要一个HTML/DOM解析器,没有其他解决方案。你不能仅仅用字符串替换HTML位置函数。@CodeCaster是的……但是……你为什么不这么说呢?不是很有建设性。虽然这个最重要的答案是天才的杰作。我想@Sammy希望在突出显示他的搜索词(或其他)后HTML可以使用,因此删除所有当前标记可能不是一个选项。此外,我不建议在HTML文档上使用XML解析器。是的!没有正确阅读:\抱歉。XML解析器可以完成我描述的工作。我编辑了我的帖子以反映我当前的工作,但需要更好的解决方案。谢谢@nickb,我会尝试一下。但我喜欢mine更好。小崽子,我只是在开玩笑。但是下面这个家伙在使用正则表达式。把你的疑虑重新集中在他身上吧!**咳嗽**(我的方法开销小得多,而且非常简单..我的意思是..有两个非常容易抓住的钩子:)不是真的…除了晦涩难懂之外,你的HTML是非常不灵活的。如果HTML明天改变了怎么办?这是灵活的、可扩展的,并且可以被增强为通用的,我只是没有努力这么做,因为这是OP问题的一个MWE。此外,评论并不是真正推广你自己答案的地方,特别是因为你的answer正在请求rep…谢谢@user1433150,我会给它一个trysence sports是一个变量($keyword),我会用$keyword替换preg\u replace\u callback()中的单词sports吗?$new=preg\u replace\u callback('/>[\w]*\s+$keyword\s+[\w]*/I',replacer',string,1);啊…我会使用
$new=preg\u replace\u callback('/>[\w]*\s+%s\s)+[\w]*/i',$keyword),'replacer',$string,1);
如果要将$replacement和$match传递给repl
$replace_string = "<span fancy colours>{$keywords}</span>";
$string = '<a href="http://my_domain_name.com/sports/info.php"><img class="icon"     src="http://my_domain_name.com/sports/images/football.gif" title="Get the latest football     sports news" alt="Get the latest football sports news" />Football sports news</a>';

$exploded = explode("<", $string);

$tmp_array = array();
foreach ($exploded as $abit) {
    $pos = (strpos($abit, ">") + 1);            //get end of tag
    $tmp_string = substr($abit, $pos);
    if (strlen($tmp_string) > 1) {  // has text outside of tags
        $tmp_string = str_ireplace($keywords, $replace_string, $tmp_string);
        $tmp_array[] = substr($abit,0,$pos) . $tmp_string;
    } else {
        $tmp_array[] = $abit;
    }
}

$newstring = implode("<", $tmp_array);
echo $newstring;
$str = '<a href="http://my_domain_name.com/sports/info.php"><img class="icon" src="http://my_domain_name.com/sports/images/football.gif" title="Get the latest football sports news" alt="Get the latest football sports news" />Football sports news</a>';

$doc = new DOMDocument();
$fragment = $doc->createDocumentFragment();
$fragment->appendXML( $str);
$doc->appendChild( $fragment);

// Create the <span>
$node = $doc->createElement( 'span');
$node->setAttribute( 'style', 'color: #000000; background-color: #FFFF00; font-weight: normal;');
$node->nodeValue = 'sports';

foreach( $doc->getElementsByTagName( 'a') as $tag)
{
    $img_tag = $tag->firstChild->cloneNode();
    $text = $doc->createTextNode( $tag->textContent);
    $tag->nodeValue = ''; // Clear out the contents of the <a>

    // Get the text before and after the replacement
    $start = strpos( $text->wholeText, 'sports');
    $before = $text->substringData( 0, $start);
    $after = $text->substringData( $start + strlen( 'sports'), strlen( $text->wholeText));

    // Put the image tag back, along with the before text, the <span>, and the after text
    $tag->appendChild( $img_tag);
    $tag->appendChild( $doc->createTextNode( $before));
    $tag->appendChild( $node);
    $tag->appendChild( $doc->createTextNode( $after));
}
echo htmlentities( $doc->saveHTML()) . "\n";
<a href="http://my_domain_name.com/sports/info.php">
    <img class="icon" src="http://my_domain_name.com/sports/images/football.gif" title="Get the latest football sports news" alt="Get the latest football sports news">Football <span style="color: #000000; background-color: #FFFF00; font-weight: normal;">sports</span> news
</a> 
function replacer($match)
{
    global $replace_match_with_this, $string_to_replace;
    return str_ireplace($string_to_replace, $replace_match_with_this, $match[0]);
}

$new_string = preg_replace_callback(sprintf('/>[^<>]*[\s-]+%s[\s-]+[^<>]*<\/a>/i', $keyword), 'replacer', $string, 1);