如何从字符串中删除链接部分之后的任何字符


How to remove anything character after the part of link from string?

我尝试过这样的方法:

$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-13);

输出功:

localhost/product/-/123456 cause this just for above link with 13 character after /-/123456

如何删除所有?我试试

$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-(.*));

不工作,犯错误。

我试试

$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-999);

输出为空。。

假设localhost/product/-/123456之后没有数字,那么我就用下面的来修剪它

$string = "localhost/product/-/123456-Ebook-Guitar";
echo rtrim($string, "a..zA..Z-"); // localhost/product/-/123456

另一个非正则表达式版本,但需要5.3.0+

$str = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo dirname($str) . "/" . strstr(basename($str), "-", true); //localhost/product/-/123456

这是一种更灵活的方式,但涉及正则表达式

$string = "localhost/product/-/123456-Ebook-Guitar";
echo preg_replace("/^([^?]*-'/'d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456
$string = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo preg_replace("/^([^?]*-'/'d+)([^?]*)/", "$1", $string); 
// localhost/product/-/123456

这应该匹配捕获数字之前的所有内容,并在之后删除所有内容

regex101:localhost/product/-/123456电子书吉他

regex101:localhost/product/-/123456-Ebok-Guitar-1-pdf/

不是一行,但这会起作用:

$string = "localhost/product/-/123456-Ebook-Guitar";
// explode by "/"
$array1 = explode('/', $string);
// take the last element
$last = array_pop($array1);
// explode by "-"
$array2 = explode('-', $last);
// and finally, concatenate only what we want
$result = implode('/', $array1) . '/' . $array2[0];
// $result ---> "localhost/product/-/123456"
相关文章: