0

I need a str_replace or anything that act after first element like this:

"Hello-World-I-am-Pr-Pro"

and That's Result I want:

"Hello-World I am Pr Pro"
4
  • 2
    And what have you tried? Commented Mar 4, 2019 at 22:39
  • im in laravel,and i find nothing Commented Mar 4, 2019 at 22:44
  • So you are looking for built-in functions to suit your custom functionality? Commented Mar 4, 2019 at 22:48
  • Maybe don' know! just wanna handle this! and need help! Commented Mar 4, 2019 at 22:50

1 Answer 1

2

The PHP regex engine will do that for you using preg_replace:

function replaceViaRegex($needle, $to, $haystack)
{
    $regexStr = '/'.preg_quote($needle, '/').'/';
    $result = preg_replace($regexStr, $to, $haystack, 1);
    return $result;
}

$foo = "Hello-World-I-am-Pr-Pro";
$foo2 = replaceViaRegex('-', ' ', $foo); 

echo $foo2;

Alternately, you could do

$foo = "Hello-World-I-am-Pr-Pro";
$regex = '/-/';
$foo2 = preg_replace($regex, ' ', $foo, 1);

... but that is far less flexible. Or even

$foo2 = preg_replace('/-/', ' ', "Hello-World-I-am-Pr-Pro", 1);

... but I've had trouble making preg_replace work in the past w/out a variable so I just avoid making it that dense.

I made the function above extremely clear and simple so that you could follow the logic and modify as you choose. You are far better off working with the first version than the other two if you want good, maintainable code.

Sign up to request clarification or add additional context in comments.

4 Comments

there is no shorter Answer?! Need Shorter! I think must be!
That is basically a 1 line fix... I'm not sure how much shorter you need. Once you add the function then replaceViaRegex('-', ' ', $foo); will do whatever you want from then on and you can vary as needed. No need to repeat code other than that single line. Does that make sense? This is an extremely common pattern in coding when you want a specific function for some result.
Alternately, you could do $foo = "Hello-World-I-am-Pr-Pro"; $foo2 = preg_replace('/-/', ' ', $foo, 1); but that is far less flexible. I made the function above extremely clear and simple so that you could follow the logic and modify as you choose.
Ty Dud! It's Help Me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.