简体   繁体   中英

replace the first 4 character with php

I have a string /en/products/saucony-switchback-iso/416.html and I would like to replace the first 4th character /en/ with /de/ .

The result should be /de/products/saucony-switchback-iso/416.html

This is what I've tried:

$href = "/en/products/saucony-switchback-iso/416.html";
$href_replace = substr_replace($href, "/de/", 0);

its only returning "/de/"?

You also need to define the length of how much you're replacing in the string, which in your case is 4 (or 3, seeing as the trailing / is present in both) characters.

$href = "/en/products/saucony-switchback-iso/416.html";
$href_replace = substr_replace($href, "/de/", 0, 4);

echo $href_replace;

If you don't define a length as in your example, it defaults to the entire length of the string http://php.net/manual/en/function.substr-replace.php

length

If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); ie end the replacing at the end of string

Which is why you're only being left with /de/

如果要替换/ en /, str_replace是更好的功能

echo str_replace("/en/", "/de/", $href);

Technically you only need to do 3 (but whatever), it's simple.

 echo "/de" .substr("/en/products/saucony-switchback-iso/416.html", 3);

Output

/de/products/saucony-switchback-iso/416.html

Sandbox

I also think substr will be about as fast as you can get it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM