preg 替换 URL 中出现的第二个子字符串


preg replace second substring occurence in url

我需要从 url 中删除子字符串的第二次出现。所以,我的网址是这样的:

http://example.com/<category>/<category>-<subcategory>-<id>

例如

http://example.com/laptop/laptop-hp-probook-101 must be http://example.com/laptop/hp-probook-101

http://example.com/computer-parts/computer-parts-cool-motherboard-123 must be http://example.com/computer-parts/cool-motherboard-123

我试过这个:

$new_url = preg_replace("$category", "", absoluteurl(<url>), 1);

但它失败了...

您可以使用反向引用:

<?php
$str = 'http://example.com/laptop/laptop-hp-probook-101';
//must be http://example.com/laptop/hp-probook-101
$str = preg_replace('/'/(.*?)'/'1-/', '/$1/', $str);
print $str;

输出:

http://example.com/laptop/hp-probook-101

试试这个

<?php 
$text = 'This is a test';
echo substr_count($text, 'is'); // 2
$url='https://www.yourdomain.com/laptops/laptops-hp-laptop-laptopid';
$arr1=explode("://",$url);
$arr2=explode("/",$arr1[1]);
$arr2[2]=str_replace ( $arr2[1]."-" , "" , $arr2[2] );
$s2=implode("/",$arr2);
$newurl=$arr1[0]."://".$s2;
echo $newurl;

您可以在此处尝试上述所有方法 http://writecodeonline.com/php/