Php Regex链接到页面上的锚
我想使用正则表达式将链接转换为页面上的锚。我对regex完全陌生,我已经尝试过学习 我已经用php字符串替换了根url中的#,但需要使用preg_replace来更改/to-而不是当/是html标记的一部分时,例如Php Regex链接到页面上的锚,php,regex,preg-replace,Php,Regex,Preg Replace,我想使用正则表达式将链接转换为页面上的锚。我对regex完全陌生,我已经尝试过学习 我已经用php字符串替换了根url中的#,但需要使用preg_replace来更改/to-而不是当/是html标记的一部分时,例如 $string = '<ul> <li><a href="http://www.somedomain.com/something/somethingelse">Hello World</a></li> <li>&
$string = '<ul>
<li><a href="http://www.somedomain.com/something/somethingelse">Hello World</a></li>
<li><a href="http://www.somedomain.com/something/somethingelse">Hello World</a></li>
</ul>';
// Replace root url with #
$string = str_replace('http://www.somedomain.com/', '#' , $string);
// This replaces the / with hyphens, but I need it to not do this if is preceeded or followed by < or >
$string = preg_replace("/\//", "-", $string);
echo $string;
$string='
';
//将根url替换为#
$string=str\u replace('http://www.somedomain.com/“,”#“,$string);
//这将用连字符替换/,但如果前面或后面有
$string=preg\u replace(“/\/”、“-”、$string);
echo$字符串;
类型:
preg_replace('/([^<]|^)\/([^>]|$)/', '$1-$2', $string);
preg_replace('/([^]|$)/','$1-$2',$string);
但是整个任务看起来不像是解决原始任务的可靠方法。谢谢您的回复,尽管我不确定它的作用是什么?我想替换/来自字符串,但如果很抱歉,则不能替换,因为有一组错误。我不知道我为什么要写这封信——也许我太累了。现在它已被修复并测试。此外,如果不需要在整个字符串的边缘使用斜杠,则可以简化正则表达式:
/([^])/s