[英]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.