我想做一些类似stackoverflow的事情。实际上改变了这种风格[]()
到这种风格<a href=""></a>
。这是我的尝试:
$str = '[link](#)';
$str = str_replace('[','<a href="',$str); // output: <a href="link](#)
$str = str_replace(']','">',$str); // output: <a href="link">(#)
$str = str_replace('(','',$str); // output: <a href="link">#)
$str = str_replace(')','</a>',$str); // output: <a href="link">#</a>
但现在,我需要改变link
与 #
,我该怎么做?
最佳答案
您想查看preg_replace()
,这样您就可以使用正则表达式来替换它,例如
$str = preg_replace("/\[(.*?)\]\((.*?)\)/", "<a href='$2'>$1</a>", $str);
正则表达式解释:
\[(.*?)\]\((.*?)\)
- \[ 匹配字符 [ 字面意义
- 第一个捕获组(.*?)
- .*? 匹配任何字符(换行符除外)
- 量词:*? 介于零次和无限次之间,尽可能少的次数,根据需要扩展[惰性]
- .*? 匹配任何字符(换行符除外)
- \] 字面匹配字符 ]
- \( 匹配字符(字面上
- 第二个捕获组(.*?)
- .*? 匹配任何字符(换行符除外)
- 量词:*? 介于零次和无限次之间,尽可能少的次数,根据需要扩展[惰性]
- .*? 匹配任何字符(换行符除外)
- \) 字面上匹配字符 )
关于php - 如何将 [link](#) 替换为 <a href ="#">link</a>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31629662/