字符串替换数值完全匹配
String replace numeric value exact match
我有字符串“http://www.test.com/abcd.html?page_num=1". I want to replace "?page_num=1" with blank string. Because I want only "http://www.test.com/abcd.html”URL.
我试过以下代码:
str_replace('?page_num=1','',$str);
但如果他们在 page_num 之后是 13,那么我得到 http://www.test.com/abcd.html3 因为替换。
您可以使用 preg_replace() 来匹配数字,如下所示:
$string = "http://www.test.com/abcd.html?page_num=12";
$res = preg_replace("/\?page_num=\d+/", "", $string);
echo $res;
我认为您可能希望使用正则表达式而不是普通的 str_replace()。 str_replace() 只会进行精确替换,而通过 RegExp 我们可以进行模式替换。
为了实现你的目标,我建议改用这个:
$str = preg_replace('#\?page_num=\d+$#i', '', $str);
如果您想了解有关 RegExp 的更多信息,请尝试 this resource
你看看,我对你的代码做了一些修改,得到了结果
首先我找到了'?'的位置并将字符串从
分解为子字符串
<?php
$str = "http://www.test.com/abcd.html?page_num=12";
$replaceString = substr($str, strpos($str, "?") );
$string = str_replace(replaceString, '', $str);
echo $string;
?>
substr(): Function returns a part of a string
strpos(): Finds the position of the first occurrence of a string inside another string
你可以通过 explode
<?php
$url = 'http://www.test.com/abcd.html?page_num=1';
echo explode('?',$url)[0];
?>
我已经解决了问题
试试这个:
$str = preg_replace('/(?<!\.)\b\?page_num=1\b(?!\.)/', '', $str);
可以通过subString获取
$url= "http://www.test.com/abcd.html?page_num=1";
$newurl = substr($url, 0, strpos($url, "?"));
我有字符串“http://www.test.com/abcd.html?page_num=1". I want to replace "?page_num=1" with blank string. Because I want only "http://www.test.com/abcd.html”URL.
我试过以下代码:
str_replace('?page_num=1','',$str);
但如果他们在 page_num 之后是 13,那么我得到 http://www.test.com/abcd.html3 因为替换。
您可以使用 preg_replace() 来匹配数字,如下所示:
$string = "http://www.test.com/abcd.html?page_num=12";
$res = preg_replace("/\?page_num=\d+/", "", $string);
echo $res;
我认为您可能希望使用正则表达式而不是普通的 str_replace()。 str_replace() 只会进行精确替换,而通过 RegExp 我们可以进行模式替换。
为了实现你的目标,我建议改用这个:
$str = preg_replace('#\?page_num=\d+$#i', '', $str);
如果您想了解有关 RegExp 的更多信息,请尝试 this resource
你看看,我对你的代码做了一些修改,得到了结果
首先我找到了'?'的位置并将字符串从
分解为子字符串<?php
$str = "http://www.test.com/abcd.html?page_num=12";
$replaceString = substr($str, strpos($str, "?") );
$string = str_replace(replaceString, '', $str);
echo $string;
?>
substr(): Function returns a part of a string
strpos(): Finds the position of the first occurrence of a string inside another string
你可以通过 explode
<?php
$url = 'http://www.test.com/abcd.html?page_num=1';
echo explode('?',$url)[0];
?>
我已经解决了问题
试试这个:
$str = preg_replace('/(?<!\.)\b\?page_num=1\b(?!\.)/', '', $str);
可以通过subString获取
$url= "http://www.test.com/abcd.html?page_num=1";
$newurl = substr($url, 0, strpos($url, "?"));