Jump to content

Preg_replace. Replace everything that does NOT match?


Recommended Posts

Hello,

 

I often find myself wanting to remove everything that does not match a pattern, or only return the matches.

 

I.e: remove everything apart from the email address (underlined) from this string '<Marius Jackson <m.jackson@example.com>'

 

or this: remove everything apart from phone number (underlined) from this string 'Marius Jackson, Norway, +47 412 43 120, Lokalrådgiver'.

 

 

I feel it would be very easy if I could use preg_filter, but my server is not PHP 5 >= 5.3.0, because I understand that this function returns only matches. And preg_match_all returns an array of all sorts of things, and i find it uncomfortable to use.

 

How do I do this easily?

 

Thanks,

Marius

 

 

The preg_match (and preg_match_all) are designed for that sort of task.  If you want a simple function to grab the matched value quickly then something like the following might work:

 

function preg_grab($pattern, $subject, $group = 0) {
    if (preg_match($pattern, $subject, $match) AND isset($match[$group]) {
        return $match[$group];
    }
    return FALSE;
}

 

Then you can call that in a similar way to preg_replace like:

$string = 'Marius Jackson <m.jackson@example.com>';
echo preg_grab($email_pattern, $string);      // m.jackson@example.com
echo preg_grab('/Marius (\w+)/', $string, 1); // Jackson

The group argument supplies a default value of 0.  Within the pattern, everything is stored within $match[0] (in this case anyway) by default. But I suspect if you wanted to ensure a capture (say first capture in a pattern, thus $match[1]) exists, you can specifiy this instead. Just gives you extra flexibility to check if a certain capture exists, as opposed to the entire base pattern ($match[0]).

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.