Otá*_*eto 1 php regex arrays function href
我有此功能来识别和转换标签,表情符号等
function convert_text($str) {
$regex = "/[@#](\w+)/";
//type and links
$hrefs = [
'#' => 'hashtag.php?hashtag',
'@' => 'user.php?user'
];
$result = preg_replace_callback($regex, function($matches) use ($hrefs) {
return sprintf(
'<a href="%s=%s">%s</a>',
$hrefs[$matches[0][0]],
$matches[1],
$matches[0]
);
}, $str);
//$result = preg_replace("/U\+([A-F0-9]{5})/", '\u{${1}}', $result);
$result = preg_replace('/U\+([A-F0-9]{5})/', '<span style="font-size:30px;">&#x\\1;</span>', $result);
return ($result);
}
Run Code Online (Sandbox Code Playgroud)
我想,使其认识http://并https://从文字和比转换为:
<a href="http://link.com">http://link.com</a>
如何在函数内部实现呢?
我的猜测是,也许您可能想写一些接近的表达式,
\bhttps?:\/\/\S*\b
Run Code Online (Sandbox Code Playgroud)
$re = '/\bhttps?:\/\/\S*\b/s';
$str = 'some text before http://some_domain.com/some_link some text before https://www.some_domain.com/some_link some text after';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
Run Code Online (Sandbox Code Playgroud)
array(2) {
[0]=>
array(1) {
[0]=>
string(32) "http://some_domain.com/some_link"
}
[1]=>
array(1) {
[0]=>
string(37) "https://www.some_domain.com/some_link"
}
}
Run Code Online (Sandbox Code Playgroud)
$re = '/(\bhttps?:\/\/\S*\b)/s';
$str = 'some text before http://some_domain.com/some_link some text before https://www.some_domain.com/some_link some text after';
$subst = '<a href="$1">$1</a>';
echo preg_replace($re, $subst, $str);
Run Code Online (Sandbox Code Playgroud)
some text before <a href="http://some_domain.com/some_link">http://some_domain.com/some_link</a> some text before <a href="https://www.some_domain.com/some_link">https://www.some_domain.com/some_link</a> some text after
Run Code Online (Sandbox Code Playgroud)
如果您想探索/简化/修改该表达式,请在regex101.com的右上方面板中进行 说明。如果愿意,您还可以在此链接中观看,它将如何与某些示例输入匹配。
jex.im可视化正则表达式: