tags:

views:

58

answers:

3

Hi guys, 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  A: 
$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
zed_0xff
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
zed_0xff
hmm... but what if there are " = " before?
then it will not work and you'll need a better function to extract data you look forposting an exact series of strings which you have will be a best help to produce such a function
zed_0xff
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 " [".
$c = split('\[1000137c\]',$s,2);$a = split(" = ",$c[1],2);$b = split(' \[',$a[1],2);$s = $c[0]."[1000137c]".$a[0].' = '.strtr($b[0],' ','_').' ['.$b[1];// this should behave better
zed_0xff
A: 

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

str_replace(" ", "_", $arr[1])
Salil
I like your solution alot more then the one above you :).
Younes
this will produce smth like:John_Rogers_III_[SOMETHING]_SOMETHING_ELSE
zed_0xff
A: 

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.

Jason