king.oslo Posted January 6, 2010 Share Posted January 6, 2010 how can I replace everything apart from a sub-pattern? For example, how do I strip everything everything apart from Q or B that are enclosed by ?'s ? This example strip everything, but I want to strip everything apart from B or Q <?php $string = 'LotsOfLetters?B?LotsOfLetters'; $regex = '~\w+\?(B|Q)\?\w+~'; $replace = ''; ?> Thanks, Marius Quote Link to comment Share on other sites More sharing options...
JAY6390 Posted January 6, 2010 Share Posted January 6, 2010 Why not just use preg_match_all and get them that way? $string = 'LotsOfL?Q?etters?B?LotsOfLe?Q??B?tters'; $regex = '%\?(B|Q)\?%'; preg_match_all($regex, $string, $out); $string = implode('', $out[0]); echo $string; Quote Link to comment Share on other sites More sharing options...
king.oslo Posted January 6, 2010 Author Share Posted January 6, 2010 How can I do this with preg_replace the way I tried to start? Thanks, Marius Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted January 6, 2010 Share Posted January 6, 2010 Hmm.. if I understand correctly, one way could be to use preg_replace_callback in conjunction with create_function, which is basically an anonymous lamda style function: $string = 'LotsOfL?Q?etters?B?LotsOfLe?Q??B?tters'; echo $string = preg_replace_callback('#(.*?)(?:\?[bQ]\?)?#', create_function('$a', 'return str_replace($a[1], "", $a[0]);'), $string); // Output: ?Q??B??Q??B? So to visualize the process, it goes something like this: Pattern = #(.*?)(?:\?[bQ]\?)?# (red denotes a captured group) LotsOfL?Q? = $a[0] - 1st iteration of the match/capture LotsOfL = $a[1] $a[1] gets replaced by empty quotes within $a[0], which leaves ?Q? to be returned. Repeat and rinse.. etters?B? = $a[0] - 2nd iteration of the match/capture etters = $a[1] $a[1] gets replaced by empty quotes within $a[0], which leaves ?B? to be returned. Etc.. Hopefully that helps. Cheers Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.