Reputation: 3261
I want to replace set of string between two characters say &
and []
with some other value. For example, my string is like &yyyyyyy[]=&gggggg[]=&bbbbb[]=
. Now I want to replace the string between &
and []
with "name" so that it looks like &name[]=&name[]=&name[]=
. Now how to do it?
Upvotes: 1
Views: 2593
Reputation: 907
This should do what you want and should match anything between & and [] that is not &, [], or =
$subject = '&yyyyyyy[]=&gggggg[]=&bbbbb[]=';
$pattern = '/&([^\[\]\&=]+)\[\]/';
$replacement = '&name[]';
echo preg_replace($pattern, $replacement, $subject, -1);
Upvotes: 0
Reputation: 1477
Something like this should do it..
using preg_replace
or preg_replace_callback
\&(.*?)\[]
this should match the strings between character & and character []
preg_match_all('#\&(.*?)\[]#','&yyyyyyy[]=&gggggg[]=&bbbbb[]=',$matches);
array(2) { [0]=> array(3) { [0]=> string(10) "&yyyyyyy[]" [1]=> string(9) "&gggggg[]" [2]=> string(8) "&bbbbb[]" }
[1]=> array(3) { [0]=> string(7) "yyyyyyy" [1]=> string(6) "gggggg" [2]=> string(5) "bbbbb" } }
this regex is the closest i can get. Hope it helps.
Upvotes: 0
Reputation: 2468
preg_replace('/&([a-zA-Z0-9]+)\[\]/', '&name[]', "&yyyyyyy[]=&gggggg[]=&bbbbb[]=");
Upvotes: 0
Reputation: 9302
$string = '&yyyyyyy[]=&gggggg[]=&bbbbb[]=';
$result = preg_replace('/&([a-zA-Z0-9]+)\[\]/', '&name[]', $string);
// Outputs: &name[]=&name[]=&name[]=
Upvotes: 3