Jump to content

Preg_replace. Replace everything that does NOT match?


king.oslo

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 <[email protected]>'

 

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 <[email protected]>';
echo preg_grab($email_pattern, $string);      // [email protected]
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]).

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.