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
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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.