[英]PHP regex: Converting and manipulating text into specific HTML
I have the following text: 我有以下文字:
I'm a link - http://google.com
I need to convert this into the following HTML 我需要将其转换为以下HTML
<a href="http://google.com">I'm a link</a>
How can I achieve this in PHP? 如何在PHP中实现呢? I'm assuming this needs some sort of regex to search for the actual text and link then manipulate the text into the HTML but I wouldn't know where to start, any help would be greatly appreciated. 我假设这需要某种正则表达式来搜索实际文本并进行链接,然后将文本操纵为HTML,但我不知道从何开始,将不胜感激。
If its always like this, you don't really need regex here: 如果它总是这样,那么您实际上不需要在这里使用正则表达式:
$input = "I'm a link - http://google.com";
list($text, $link) = explode(" - ", $input);
echo "<a href='". $link ."'>". $text ."</a>";
If a regex is needed, here's a fully function code: 如果需要正则表达式,请使用以下完整功能代码:
<?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;
?>
Example here: http://phpfiddle.io/fiddle/1166866001 此处的示例: http : //phpfiddle.io/fiddle/1166866001
If it's always one line of text though, it would be better to go with 1nflktd solution. 如果始终是一行文本,最好使用1nflktd解决方案。
Try with capturing groups and substitution: 尝试捕获组和替换:
^([^-]*) - (.*)$
Sample code: 样例代码:
$re = "/^([^-]*) - (.*)$/i";
$str = "I'm a link - http://google.com";
$subst = '<a href="$2"">$1</a>';
$result = preg_replace($re, $subst, $str);
Output: 输出:
<a href="http://google.com"">I'm a link</a>
Pattern Explanation: 模式说明:
^ 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.