[英]Linkify with provided text in PHP
我個人對preg_replace
不是很好,如果可能的話可以使用一些幫助。
我想鏈接一個字符串並允許一個可選的文本參數。 例子:
輸入:
[[http://www.example.com/path/to/file.ext]]
Output:
<a href="http://www.example.com/path/to/file.ext">http://www.example.com/path/to/file.ext</a>
輸入:
[[http://www.example.com/path/to/file.ext "click here"]]
Output:
<a href="http://www.example.com/path/to/file.ext">click here</a>
我將如何做到這一點(如果可能的話使用preg_replace
)?
先感謝您。
試試這個 regx,你想匹配 [[stuff]],對吧?
/\[\[(?P<link>[^\s]+)\s(?P<text>[^\]]+)\]\]/
https://regex101.com/r/pT4bL1/1
我幫助你鏈接,但不知道你是如何創建它們的。 例如,將 preg_match 與第三個參數一起使用,您將擁有[[]]
中的部分,然后就可以了
if( preg_match('/\[\[(?P<link>[^\s]+)\s(?P<text>[^\]]+)\]\]/', '[[http://www.example.com/path/to/file.ext "click here"]]', $match ) ){
echo '<a href="'.$match['link'].'">'.$match['text'].'</a>';
}
解釋regx
\[\[
- 只是 [[(?P<link>[^\s]+)
- (?P<name>..,)
被命名為捕獲組[^\s]+
除了空格。\s
一個空格(?P<text>[^\]]+)
除了[^\]]+
與上面相同,除了 ]\]\]
- 結尾 ]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.