如何用包含相同数字的 link 替换字符串中的数字

How to replace numbers in string with link containing the same number

我有一个简单的 HTML 页面,其中包含数字列表。像这样:

Look at the following pages: 23, 509, 209, 11, 139, 68, 70-72, 50, 409-412

我想用这样的超链接替换每个数字或范围:

<a href="www.mysite.com?page=23">23</a>, <a href="www.mysite.com?page=509">509</a> ..... <a href="www.mysite.com?page=409">409-412</a>

数字只有两位和三位数字,除首位和末位外用逗号括起来。还有一些范围,例如 391-397

只有当您确定源字符串的模式时才会这样做

$numbers = "23, 509, 209, 11, 139, 68, 70-72, 50, 409-412";
$output = "";
$numbers = explode(",",$numbers);//split the string into array (NOTE:only if you trust the pattern of the string)

foreach($numbers as $number){
     $number = str_replace(" ","", $number); // remove the space that is after the comma if there is
     $range = explode("-",$number); // if it is a range it will be splitted
     $output .= "<a href='www.mysite.com?page=".$range[0]."'>$number</a> ";
}
echo $output;

HTML 注意:像这样设置 href 属性 www.mysite.com 将导致浏览器在当前文档位置之后跟踪它的值,因此它将是这样的

 https://www.example.com/currentlocation/www.mysite.com?page=23

我猜这就是你想要的

<a href='https://www.example.com?page=23'>

您可以使用PHP preg_replace()来实现您想要的。

$original_string = 'Look at the following pages: 23, 509, 209, 11, 139, 68, 70-72, 50, 409-412';

$updated_string = preg_replace(
   '~((\d{2,3})(\-\d{2,3})?)~', 
   '<a href="//www.mysite.com?page="></a>', 
   $original_string
);

echo $updated_string;

看到它工作 here

preg_replace() 的第一个参数中的 () 部分可以在第二个参数中用 </code>、<code> 等引用...第一个封闭部分 ( </code>) 是页码或页码范围(“23”、“70-72”)。第二个封闭部分 (<code>) 是页码或页面范围的第一个数字。

在线有很多资源提供有关正则表达式的更多信息,您可以试用我编写的正则表达式 here