在html文件中,我有这样的链接
<a href="index_split_037.xhtml#id145937_n22">
.
我如何修改它们,以便在处理后它变成
<a href="#id145937_n22">
.
基本上,我只需要保留主题标签。
正则表达式:
(<a href=")[^#]*([^>]*>)
替换字符串:
'1'2
演示
例:
<?php
$mystring = "The input string foo <a href='"index_split_037.xhtml#id145937_n22'"> bar";
echo preg_replace('~(<a href=")[^#]*([^>]*>)~', ''1'2', $mystring);
?>
输出:
The input string foo <a href="#id145937_n22"> bar
解释:
-
(<a href=")
字符串<a href="
由组 1 捕获。 -
[^#]*
匹配任何不是零次或更多次#
字符。 找到符号#
后,正则表达式引擎将停止匹配操作。 -
([^>]*>)
同样,组 2 捕获以下字符,直到下一个>
符号。 - 在替换部分中,我们将匹配的字符替换为捕获组中的字符。
(.*?")(?:.*?)(#.*)
请参阅演示。
http://regex101.com/r/yM7jY2/1
您可以使用
ob_start
来捕获输出,并使用preg_replace
来更改href
属性:
<?php
ob_start(); // Capture the output
?>
<!--- Links --->
<a href="index_split_037.xhtml#id145937">Link 1</a>
<a href="index_split_038.xhtml#id147_n22">Link 2</a>
<a href="index_split_039.xhtml#id_n22">Link 3</a>
<a href="index_split_040.xhtml#145937_n22">Link 4</a>
<?php
$output = ob_get_contents(); // Get the output
ob_end_clean(); // Finish capture
// Remove the letters in href attribute before the hash # maintaining the others attributes
echo preg_replace('/<a(.*)href="([^"#]*)#([^"]*)"(.*)>/','<a$1href="#$3"$4>', $output);
?>
请参阅正则表达式:http://regexr.com/39bmb。查看示例的工作原理:沙盒示例。