str_replace,在单词php后面添加一个斜杠


str_replace by adding a slash after a word php

基本上我有这个urlhttp://xxxxxxx.xxx/example.com/category-1sub-category-11/products.html我有这个字符串CCD_ 1,我想在字符串之前添加一个斜线,如下所示:http://xxxxx.xxx/example.com/category-1/sub-category-11/products.html.

$url = 'http://localhost/example.com/category-1sub-category-11/products.html';
$string = 'sub-category-11';
$new_url = preg_replace('/'b'.$string.''b/', '/'.$string, $url);

有什么帮助吗?非常感谢。

也许这。。。

$new_url = str_replace($string, '/' . $string, $url);

您可以将str_replace用于此目的。只需将类别-1替换为类别-1/

<?php
$url = 'http://localhost/example.com/category-1sub-category-11/products.html';
$string = 'category-1';
$new_url = str_replace($string, $string.'/', $url);

或具有/子类别-11 的子类别-11

<?php
$url = 'http://localhost/example.com/category-1sub-category-11/products.html';
$string = 'sub-category-11';
$new_url = str_replace($string, '/' . $string, $url);

希望这能帮助您