Php 如何使用preg_replace_回调代替preg_replace以链接html替换单词?
我试图在if语句中使用preg_match(),它们是preg_replace()。它工作得很好,直到我发现preg_replace已经去润滑,应该用preg_replace_callback替换。所以我更换了它,但运气不好,它不工作,我需要你的帮助,请理解我应该如何使用它在我的情况下。我在stackoverflow和其他地方读过其他问题,但没有一个与我的情况类似Php 如何使用preg_replace_回调代替preg_replace以链接html替换单词?,php,Php,我试图在if语句中使用preg_match(),它们是preg_replace()。它工作得很好,直到我发现preg_replace已经去润滑,应该用preg_replace_callback替换。所以我更换了它,但运气不好,它不工作,我需要你的帮助,请理解我应该如何使用它在我的情况下。我在stackoverflow和其他地方读过其他问题,但没有一个与我的情况类似 // The Regular Expression filter $reg_exUrl1 = "/(http|https|ftp|f
// The Regular Expression filter
$reg_exUrl1 = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text
if(preg_match($reg_exUrl1, $discussion_text_with_links, $url1)) {
// make the urls hyper links
//$replaceWith = "<a href=".$url1[0]." class='hashtag_link' target='_blank'>".$url1[0]."</a> ";
$discussion_text_with_links = preg_replace_callback($reg_exUrl1, function($url1) {echo "<a href=".$url1[0]." class='hashtag_link' target='_blank'>".$url1[0]."</a> ";}, $discussion_text_with_links);
} else {
// The Regular Expression filter
$reg_exUrl2 = "/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text
if(preg_match($reg_exUrl2, $discussion_text_with_links, $url1)) {
// make the urls hyper links
//$replaceWith = "<a href=".$url1[0]." class='hashtag_link' target='_blank'>".$url1[0]."</a> ";
$discussion_text_with_links = preg_replace_callback($reg_exUrl2, function($url1) {echo "<a href=".$url1[0]." class='hashtag_link' target='_blank'>".$url1[0]."</a> ";}, $discussion_text_with_links);
}
}
//正则表达式筛选器
$reg|U exUrl1=“/(http | https | ftp | ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/”;
//检查文本中是否有url
if(预匹配($reg\U exUrl1,$DISPLATION\U text\U with\U links,$url1)){
//使URL成为超链接
//$replacetwith=“”;
$discussion_text_with_links=preg_replace_回调($reg_exUrl1,函数($url1){echo”“;},$discussion_text_with_links);
}否则{
//正则表达式过滤器
$reg_exUrl2=“/[a-zA-Z0-9\-\.]+.[a-zA-Z]{2,3}(\/\S*)?/”;
//检查文本中是否有url
if(预匹配($reg\u exUrl2,$discussion\u text\u带链接,$url1)){
//使URL成为超链接
//$replacetwith=“”;
$discussion_text_with_links=preg_replace_回调($reg_exUrl2,函数($url1){echo”“;},$discussion_text_with_links);
}
}
您不需要preg\u replace\u callback()
。只需在preg_replace()
的替换字符串中使用$0
,它将被替换为与regexp匹配的字符串
$discussion_text_with_links = preg_replace(
$reg_exUrl1,
"<a href='$0' class='hashtag_link' target='_blank'>$0</a>",
$discussion_text_with_links);
$discussion\u text\u with\u links=preg\u replace(
$reg_exUrl1,
"",
$discussion\u text\u(带链接);
您还可以使用
$1
、$2
等来引用捕获组。您在哪里听说preg_replace()
不推荐使用?唯一不推荐使用的是e
修饰符,这是创建替换时执行代码的旧方法。如果只是复制捕获组,就不需要这样做。我在php网站oops上读到了关于Debricated的文章!!我误解了!这可能是因为我从未使用过e修饰符,这正是我刚才所说的:preg_replace()/e修饰符现在已不推荐使用。它并没有说preg\u replace()
本身就不受欢迎。