Shan
Shan

Reputation: 2832

How to match special character using preg_match in php?

I have this

$content1="W've have come across";
$content2="W've have come across all the oceans but still we don't find anything";

I have to strip out the content between "We've have come across" and "anything"

What kind of regex should I use when the content1,content2 can change but they may contain apostrophe's or special characters?

How to use preg_match when you have special characters?

Upvotes: 1

Views: 1513

Answers (3)

Shikiryu
Shikiryu

Reputation: 10219

Without regexp, I'd use this :

function weirdExtract($str, $start, $end){
    $posa = strripos($str, $start);
    $posb = strripos($str, $end);
    if($posa === false || $posb === false) return '';
    $startlen = strlen($start);
    return substr($str, $posa + $startlen, $posb - $startlen);
}

Used like this : http://codepad.viper-7.com/BJmEGG

strripos() can be changed with the appropriate function if case is important.

Upvotes: 0

Tomas
Tomas

Reputation: 59585

I use something like this:

function escape_regexp($regexp)
{
        $regex_chars = '^.[]$()|*+?{}' . "\\";
        $regexp = addcslashes($regexp, $regex_chars);

        return $regexp;
}

and then e.g. call:

preg_replace('/something' . escape_regexp($var1) . 
    'something else/', '', $string)

I didn't use preg_quote() because I wanted function for general regexp escaping, not just for PHP, but also for mysql. I wanted a different character set. I didn't want charactes < and > to be escaped - I didn't find reason for escaping them.

Upvotes: 0

gaRex
gaRex

Reputation: 4235

preg_quote should help you, but as @Tomalak said -- why don't you want to use str_replace or something simple (not regexps)?

Upvotes: 4

Related Questions