2011-06-27 37 views
0

我想用正则表达式将链接转换为页面锚点。我对正则表达式很陌生,我试过学习。正则表达式链接到页面锚点

我已经使用php字符串替换为根网址,但需要使用preg_replace来更改/而不是当/是诸如<//>之类的html标记的一部分时。

$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; 

回答

1

种类:

preg_replace('/([^<]|^)\/([^>]|$)/', '$1-$2', $string); 

但整个任务看起来并不像解决原始任务的可靠方法。

+0

感谢您的回复,虽然我不确定它是干什么的?我想替换/从一个字符串,但不是如果它是 Jason

+0

对不起,有一系列的错误。我不知道我为什么写这个 - 也许我太累了。现在它已经过修复和测试。 –

+1

此外,正则表达式可以简化,如果你不需要整个字符串边缘的斜杠:'/([^ <])\/([^>])/ s' –