replace替换HTML标记

replace替换HTML标记

本文介绍了PHP函数使用preg_replace替换HTML标记(例如元描述)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我获得这个功能吗?该函数应该接受使用 DOMDocument 被推荐为alre如果你正在用正则表达式挣扎,那么我可能会帮你解决问题。您可以试试这个:

  return preg_replace('/< meta name =descriptioncontent =(。*) \ /> / i','< meta name =descriptioncontent =Something replaced/>',$ HTMLstr); 


Can someone help me get this function to work? The function should accept $HTMLstr -- a whole page of HTML stuffed into a string that already contains a meta description in the form of:

<meta name="description" content="This will be replaced"/>

along with $content which is the string that should replace "This will be replaced". I thought I was close with this function, but it doesn't quite work.

function HTML_set_meta_description ($HTMLstr, $content) {
$newHTML = preg_replace('/<meta name="description"(.*)"\/>/is', "<meta name=\"description\" content=\"$content\"/>", $HTMLstr);
return ($newHTML);
}

Thanks for any help!

Edit: Here's the working function.

function HTML_set_meta_description ($HTMLstr, $content) {
// assumes meta format is exactly <meta name="description" content="This will be replaced"/>
$newHTML = preg_replace('/<meta name="description" content="(.*)"\/>/i','<meta name="description" content="' . $content . '" />', $HTMLstr);
return ($newHTML);

}

解决方案

Using DOMDocument is recommended as already an answer, however if you're struggling with a regular expression, then I might help you out. You might try this instead:

return preg_replace('/<meta name="description" content="(.*)"\/>/i','<meta name="description" content="Something replaced" />', $HTMLstr);

这篇关于PHP函数使用preg_replace替换HTML标记(例如元描述)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:35