4

Suppose I have a string like this

SOMETHING [1000137c] SOMETHING = John Rogers III [SOMETHING] SOMETHING ELSE

and I need to turn it into this

SOMETHING [1000137c] SOMETHING = John_Rogers_III [SOMETHING] SOMETHING ELSE

Therefor I need to replace spaces with "_" between words after "[1000137c] SOMETHING = " and before " [". How can I do that in php?

Thanks!

3 Answers 3

3
$s = "SOMETHING [1000137c] SOMETHING = John Rogers III [SOMETHING] SOMETHING ELSE";
$a = split(" = ",$s,2);
$b = split(' \[',$a[1],2);
$s = $a[0] . ' = ' . strtr($b[0],' ','_') . ' [' . $b[1];

print_r($s);

produces:

SOMETHING [1000137c] SOMETHING = John_Rogers_III [SOMETHING] SOMETHING ELSE
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, I'll try to get it working. Only that there could be more then one " = " in the string. The only thing we know for certain, is that name comes after "[1000137c] SOMETHING = ", the 1000137c does not repeat.
this will work if there's no " = " substrings before a mentioned one. everything will work fine if they're after it
hmm... but what if there are " = " before?
then it will not work and you'll need a better function to extract data you look for posting an exact series of strings which you have will be a best help to produce such a function
there can be all sorts of characters and sub-strings both before and after "[1000137c] SOMETHING = John_Rogers_III [". What we know for sure is that the name, where we have to replace spaces with "_" comes after "[1000137c] SOMETHING = " and before " [".
|
0

$arr = split a string in an array on "=" and then

str_replace(" ", "_", $arr[1])

2 Comments

I like your solution alot more then the one above you :).
this will produce smth like: John_Rogers_III_[SOMETHING]_SOMETHING_ELSE
0

using a regex like so "/^[\w ]+[[\w\d]+] [\w]+ = ([\w\d ]+) [[\w\d]+] [\w ]+$/i" should return match 1 as "John Rogers III", though this based on the current example.

using preg_replace_callback with the above regex, you can str_replace to replace the spaces with underscores in the callback function.

Comments

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.