[英]PHP: process all regex matches
在我正在處理的網站上,用戶可以創建自己的頁面,他們可以上傳他們的作品,如音樂,藝術,圖片等。
每個頁面都有一個“關於此頁面”部分,用戶可以在其中放置所需的信息。 我們希望擴展它並允許它們使用自定義標記,例如鏈接,圖像等......
現在,我一直堅持添加鏈接標記,我想用於標記的格式是:
[link]http://url.com,descriptyion[/link]
它需要轉換為:
<a href='http://url.com'>desciption</a>
問題是,包含標記的描述是段落格式,並且有多個鏈接:
This is a page description that will contain multiple link markups such
as [link]http://url.com,this[/link] and [link]http://url.com,this too[/link].
我知道如何正則表達式,並捕獲結果,但我從來沒有必要處理更復雜的這樣的事情...我的大腦只是在3小時的思考之后停止工作,因為我甚至不知道從哪里開始。
總結一下我的問題:我需要從段落中找到所有正則表達式匹配,處理匹配然后將其注入到同一位置的段落。
您需要將preg_replace與一些正則表達式組一起使用
$str = ' This is a page description that will contain multiple link markups such
as [link]http://url.com,this[/link] and [link]http://url.com,this too[/link].';
echo preg_replace('#\[link\](.*?),(.*?)\[\/link\]#', '<a href="$1">$2</a>', $str);
同樣重要的是要逃避像[ ] \\
等正則表達式使用的一些字符。
根據史蒂夫的評論,我建議使用Markdown。
如果你真的想要一個自定義鏈接語法,像這樣的正則表達式就足夠了:
$outputString = preg_replace('/\[link\]([^,\[\]]+),([^,\[\]]+)\[\/link\]/i', '<a href="\\1">\\2</a>', $inputString);
示例測試:
$inputString = 'This is a page description that will contain multiple link markups such
as [link]http://url.com,this[/link] and [link]http://url.com,this too[/link].';
$expectedOutputString = 'This is a page description that will contain multiple link markups such
as <a href="http://url.com">this</a> and <a href="http://url.com">this too</a>.';
$actualOutputString = preg_replace('/\[link\]([^,\[\]]+),([^,\[\]]+)\[\/link\]/i', '<a href="\\1">\\2</a>', $inputString);
if ($expectedOutputString === $actualOutputString) {
echo 'CORRECT';
} else {
echo 'INCORRECT';
echo $expectedOutputString . ' !== ' . $actualOutputString;
}
// OUTPUT: CORRECT
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.