0

I am beginner in php, and i have problems with replace & explode

I want to replace strings using ":" all strings is unknown!

input :

string1:string2:string3:string4:
have:a:good:day:
link1:link2:link3:link4:

output :

string1:string2:newString:string4:
have:a:newString1:day:
link1:link2:newString3:link4:
2
  • stackoverflow.com/questions/535143/… Commented Jun 28, 2017 at 22:00
  • Where do the replacements come from? Are you always replacing the third field, or are you replacing specific words? Commented Jun 28, 2017 at 22:45

1 Answer 1

1

I think you're looking for the explode and implode functions. You can do something like this which breaks your string into an array, you can modify the array elements, then combine them back into a string.

$str = "have:a:good:day:";

$tokens = explode(":", $str);
//$tokens => ["have", "a", "good", "day", ""]

$tokens[2] = "newString1";
//$tokens => ["have", "a", "newString1", "day", ""]

$str2 = implode(":", $tokens);
//$str2 => "have:a:good:day:"

Alternatively if you just want to replace certain words in the string, you can use the str_replace function to replace one word with another. Eg.

$str = "have:a:good:day:";
$str2 = str_replace("good", "newString1", $str);
//$str2 => "have:a:newString1:day:";
Sign up to request clarification or add additional context in comments.

4 Comments

Why would somebody use implode and explode for string replace?
He asked about explode. Could be that he wants to replace element N, not replace based on text. I expanded my answer to cover both cases, though.
But he didn't about implode and this code is just overkill for that simple task. If so, show him real solution with string replace and array tokens.
You're assuming you know the use case is just to replace one string value with another, it was not clear from the question so I covered that approach as well if they want to do a replace based on the element's "position" in the string. If you are not happy with my answer I cannot help you. There are two "real" solutions in my answer. EDIT: From the OP's edit to their post, it appears this was the correct approach, where the strings are unknown.

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.