Roger Travis
Roger Travis

Reputation: 8538

how do I replace certain characters in a string?

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!

Upvotes: 4

Views: 577

Answers (3)

Jason
Jason

Reputation: 2049

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.

Upvotes: 0

Salil
Salil

Reputation: 47472

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

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

Upvotes: 0

zed_0xff
zed_0xff

Reputation: 33217

$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

Upvotes: 3

Related Questions