Php 修改html中的所有链接以仅保留哈希标记
在html文件中,我有如下链接Php 修改html中的所有链接以仅保留哈希标记,php,regex,Php,Regex,在html文件中,我有如下链接 我如何在流程完成后修改它们 基本上,我只需要保留标签。Regex: (<a href=")[^#]*([^>]*>) 例如: <?php $mystring = "The input string foo <a href=\"index_split_037.xhtml#id145937_n22\"> bar"; echo preg_replace('~(<a href=")[^#]*([^>]*>)~'
我如何在流程完成后修改它们
基本上,我只需要保留标签。Regex:
(<a href=")[^#]*([^>]*>)
例如:
<?php
$mystring = "The input string foo <a href=\"index_split_037.xhtml#id145937_n22\"> bar";
echo preg_replace('~(<a href=")[^#]*([^>]*>)~', '\1\2', $mystring);
?>
见演示
您可以使用来捕获输出并更改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);
?>
链接像什么?它会变成什么?谢谢,蛇。您拥有最完整的替换正则表达式规则。当做!
The input string foo <a href="#id145937_n22"> bar
(.*?")(?:.*?)(#.*)
<?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);
?>