[英]PHP regex: Converting and manipulating text into specific HTML
我有以下文字:
I'm a link - http://google.com
我需要将其转换为以下HTML
<a href="http://google.com">I'm a link</a>
如何在PHP中实现呢? 我假设这需要某种正则表达式来搜索实际文本并进行链接,然后将文本操纵为HTML,但我不知道从何开始,将不胜感激。
如果它总是这样,那么您实际上不需要在这里使用正则表达式:
$input = "I'm a link - http://google.com";
list($text, $link) = explode(" - ", $input);
echo "<a href='". $link ."'>". $text ."</a>";
如果需要正则表达式,请使用以下完整功能代码:
<?php
$content = <<<EOT
test
http://google.com
test
EOT;
$content = preg_replace(
'/(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/',
'<a href=\'$0\'>I\'m a link</a>',
$content
);
echo $content;
?>
此处的示例: http : //phpfiddle.io/fiddle/1166866001
如果始终是一行文本,最好使用1nflktd解决方案。
尝试捕获组和替换:
^([^-]*) - (.*)$
样例代码:
$re = "/^([^-]*) - (.*)$/i";
$str = "I'm a link - http://google.com";
$subst = '<a href="$2"">$1</a>';
$result = preg_replace($re, $subst, $str);
输出:
<a href="http://google.com"">I'm a link</a>
模式说明:
^ the beginning of the string
( group and capture to \1:
[^-]* any character except: '-' (0 or more times)
) end of \1
- ' - '
( group and capture to \2:
.* any character except \n (0 or more times)
) end of \2
$ before an optional \n, and the end of the string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.