[英]Multiple regex in function using php
I wanted to pass data that contains url
within it, and the url
will be converted to click-able links, but the issue is that when i run the function
, it reiterate 3 times and the data is treated 3 times. 我想传递其中包含
url
数据,并且该url
将转换为可单击的链接,但是问题是,当我运行该function
,它会重复3次,并将数据处理3次。 How can I have a single data output? 如何获得单个数据输出? I tried removing the concatenation
.=
to just =
but then, only the last pattern is being treated. 我尝试将串联
.=
删除为just =
但是,仅处理了最后一个模式。 I want it in 3 pattern because I want to add http
to the href
when a user input is www.ivotism.com
, it will be <a href="http//www.ivotism.com">www.ivotism.com</a>
instead of <a href="www.ivotism.com">www.ivotism.com</a>
. 我想要3种模式,因为当用户输入为
www.ivotism.com
,我想将http
添加到href
,它将是<a href="http//www.ivotism.com">www.ivotism.com</a>
代替<a href="www.ivotism.com">www.ivotism.com</a>
。
function linkify($inputText) {
//URLs starting with http://, https://, or ftp://
$replacePattern1 = '/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i';
$replacedText .= preg_replace($replacePattern1, '<a href="$1" target="_blank">$1</a>', $inputText);
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
$replacePattern2 = '/(^|[^\/])(www\.[\S]+(\b|$))/i';
$replacedText .= preg_replace($replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>', $inputText);
//Change email addresses to mailto:: links.
$replacePattern3 = '/(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/i';
$replacedText .= preg_replace($replacePattern3, '<a href="mailto:$1">$1</a>', $inputText);
return $replacedText;
}
I run the code as shown below: 我运行如下代码:
$ab = "<br>1 http://www.ivotism.com <br>2 https://www.ivotism.com/hom.php?u=kira&id=2 <br>3 ftp://www.ivotism.com <br>4 w www.ivotism.com <br>5 info@ivotism.com"; echo
linkify($ab);
This is the result I got: 这是我得到的结果:
You can perform all the replacements in a single call to preg_replace
, by putting the regular expressions and replacements into arrays. 通过将正则表达式和替换项放入数组中,您可以在一次调用
preg_replace
执行所有替换项。
$resultText = preg_replace(array($replacePattern1, $replacePattern2, $replacePattern3),
array($replaceSub1, $replaceSub2, $replaceSub3),
$inputText);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.