Jump to content

how can I replace everything apart from...


king.oslo

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/187413-how-can-i-replace-everything-apart-from/
Share on other sites

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.