开发者

First instance in string

I have a string, say:

www.google.com/tomato.mdm

I need to replace tomato with tomaton (add n to it). My method is to find the . then replace it with n. . This didn't work. Tomato can be many differe开发者_运维知识库ny words, so I can't just search for that either...

Is their any way to solve this?

I thought about only replacing it at the first instance from the end, but cannot find a function to do this in the php manuel.


I would approach it like this:

$string = "www.google.com/tomato.mdm";
$lastDot = strrpos($string, '.');
$newString = substr($string, 0, $lastDot) . 'n.' . substr($string, $lastDot + 1);

I use strrpos to find the last occurrence of "." in the string. Then I split the string in two parts (using substr): Everything before the last dot, and everything after it. I then insert "n." between those two parts, which should give the desired result.

A solution using regular expression would be the following:

$string = "www.google.com/tomato.mdm";
$newString = preg_replace('/(.*?)(\.[^\.]*)$/', '\1n\2', $string);

See preg_replace and a regex reference for more info.


You should use Regex to do this

 $newStr = preg_replace("#^(www.google.com/[a-zA-z]*)#", '$1n', "www.google.com/tomato.mdm");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜