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

Php 如何从字符串中删除链接部分后的任何字符?,php,string,Php,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+)")-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+)")-(.*));
不工作和错误sintax

我试着

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

输出为空。

不是一行,但这将实现以下目的:

$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"

假设
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
这应该匹配捕获数字之前的所有内容,然后删除所有内容


您想要的输出是什么?如果我尝试strpos(strev($string),“-/(0-9+)-13);还有工作!就像这里一样,长角色怎么样?删除strpos之后的任何内容(strrev($string),“-/(0-9+))?);我只希望输出localhost/product/-/123456,然后全部删除..strpos不支持regex,它可以工作,因为它发现
-/
的位置很好,我怎么没有想到这一点!感谢Andrew和CJ Nimes完成这项工作。。美好的我很快乐;()@netboy78,如果提供的解决方案有效,请将答案向上投票以结束问题。@cj如果字母Aa到Zz并在数字后加上破折号,则只进行此修剪,如果除此之外还有其他字符,则无法按预期工作。@netboy78是,那么您可能会想使用regex one,因为它涉及到更复杂的字符串操作。非常感谢CJ Nimes。。我忘记回显($结果);这一结果;)现在是工作!!谢谢!!