PHP函数使用preg_replace替换HTML标记(例如元描述) [英] PHP function to replace a HTML tag (e.g. meta description) using preg_replace
本文介绍了PHP函数使用preg_replace替换HTML标记(例如元描述)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ HTMLstr
- 整个HTML页面填充到已包含元描述的字符串中: < meta name =descriptioncontent =This will be replaced/>
以及 $ content
这是字符串应该取代这将被取代。
函数HTML_set_meta_description($ HTMLstr,$ content)这个函数的功能非常接近,但它不起作用。 {
$ newHTML = preg_replace('/< meta name =description(。*)\ /> / is','< meta name = \description \content = \\ ($ newHTML);
}
$
感谢您的帮助!
编辑:这里是工作函数。
函数HTML_set_meta_description($ HTMLstr,$ content){
//假设meta格式正好< meta name =descriptioncontent =This will be replaced/> ;
$ newHTML = preg_replace('/< meta name =descriptioncontent =(。*)\ /> / i','< meta name =descriptioncontent =' $ content。'/>',$ HTMLstr);
return($ newHTML);
}
解决方案使用
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标记(例如元描述)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文