TheMayhem Posted May 9, 2011 Share Posted May 9, 2011 Pretty basic question here, I have a string called: $string I want to use a php replace function or whatever would be best to find the first occurence of ] and for the string to delete from ] And everything after that first occurence of ] In the string. Example $string = "Hello Friends [Test] My name is John"; After the php function $string "Hello Friends [Test"; Quote Link to comment https://forums.phpfreaks.com/topic/235884-replace-first-occurrence/ Share on other sites More sharing options...
Zane Posted May 9, 2011 Share Posted May 9, 2011 $string = preg_replace("@(.*)\]@", $1, "Hello Friends [Test] My name is John"); Quote Link to comment https://forums.phpfreaks.com/topic/235884-replace-first-occurrence/#findComment-1212570 Share on other sites More sharing options...
fugix Posted May 9, 2011 Share Posted May 9, 2011 $string = "Hello Friends [Test] My name is John"; $strpos = strpos($string, ']'); $substr = substr($string,0,$strpos); should be what you are looking for Quote Link to comment https://forums.phpfreaks.com/topic/235884-replace-first-occurrence/#findComment-1212571 Share on other sites More sharing options...
.josh Posted May 9, 2011 Share Posted May 9, 2011 $string = array_shift(explode(']',$string)); Quote Link to comment https://forums.phpfreaks.com/topic/235884-replace-first-occurrence/#findComment-1212576 Share on other sites More sharing options...
.josh Posted May 9, 2011 Share Posted May 9, 2011 $string = preg_replace("@(.*)\]@", $1, "Hello Friends [Test] My name is John"); This won't work. First off, you need to wrap $1 in quotes in the replace argument. 2nd, this pattern will greedily match everything to the end of the string and then give up characters until it finds a ] so IOW it will actually match for the last occurrence of ] in the string. And then the $1 will replace everything it matched before that so IOW this pattern just removes the last occurring ] in the string preg_replace approach would be more like "~^([^\]]*).*~" Basically you have to use a pattern that matches the entire string. More efficient would be to use preg_match and just match the bit you actually want. More efficient would be to use other functions like strpos, substr, explode, etc.. Quote Link to comment https://forums.phpfreaks.com/topic/235884-replace-first-occurrence/#findComment-1212578 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.