我正在尝试在字符串中查找不是来自<img>
的网址。例如:
$string = "lorem ipsum http://google.com dolor sit amet <img src="http://img.com/img.png" />;
要:
lorem ipsum http://google.com dolor坐下来 &LT; img src =&#34; http://img.com/img.png" /&gt;
我试过了:
function make_clickable($text) {
$regex = '#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#';
return preg_replace_callback($regex, function ($matches) {
return "<p><a href='{$matches[0]}' class='link'>{$matches[0]}</a></p>";
}, $text);
$matches = array();
}
编辑: 那可能是这样的:
function make_clickable($text) {
$regex = '#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#';
return preg_replace_callback($regex, function ($matches) {
return "<p><a href='{$matches[0]}' class='link'>{$matches[0]}</a></p>";
}, $text);
$matches = array();
}
$string = preg_replace('/\bsrc="http\b/u', 'src="htt-p', $string);
$string = make_clickable($string);
$string = preg_replace('/\bsrc="htt-p\b/u', 'src="http', $string);
echo $string;
答案 0 :(得分:0)
这样做。有关其工作原理的简短说明可在代码注释中找到:
<?php
# fixed syntax error string
$string = "lorem ipsum http://google.com dolor sit amet <img src=\"http://img.com/img.png\" />";
function make_clickable($text) {
# explode string on spaces to array
$arr = explode(' ', $text);
# test each array element if it contains nothing else but a website
foreach($arr as $key => $value){
if(preg_match('#((^https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i', $value)){
# replace plain text urls with href links in array
$arr[$key] = "<p><a href='". $value ."' class='link'>". $value ."</a></p>";
}
}
# rebuild array back to string
$text = implode(' ', $arr);
# return result
return $text;
}
echo make_clickable($string);
?>