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


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

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

请看以下几页: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

您可以使用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=$2">$1</a>', 
   $original_string
);
echo $updated_string;

看它在这里工作

preg_replace()第一个参数中的()部分可以与$1$2等在第二个参数中引用。第一个封闭的部分($1)是页码或页范围("23","70-72")。第二个封闭的部分($2)是页范围的页码或第一个页码。

网上有很多关于正则表达式的更多信息,你可以使用我在这里写的正则表达式。

这仅在您确定源字符串

的模式时才会出现。
$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;
注意:将href属性设置为www.mysite.com将导致浏览器跟踪它的值在当前文档位置之后所以它将是这样的
 https://www.example.com/currentlocation/www.mysite.com?page=23

我猜这就是你想要的

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