tags:

views:

134

answers:

4

How do strip all regex special characters from a string?

eg: I have "/^bla\/bla\/bla\//i" which I want to be: "bla/bla/bla/"

A: 

I don't understand exactly what you're trying to do, but if you just want to remove certain characters from a string you might be better off using strtr(). For one thing it'll be much faster than doing a regex, and it'll probably be more readable as well.

edit: Actually I really don't understand what you're trying to achieve.

therefromhere
The OP didn't say he was trying to *use* a regex, but rather trying to *transform* a regex representing a string into another string.
Avi
Yeah, I realised that after I posted. Now I'm confused.
therefromhere
Perhaps it's better to remove this answer then?
Bart Kiers
Well, I'll admit, it's a pretty poorly formed question, i.e. it would be better to see real data, and the real desired outcome, and then we could define a more elegant solution...
A: 
    <?php 
    $string = "/^bla\/bla\/bla\//i";
    $patterns = array(
        "/\/\^([\w]+)/i" => "$1/",
        "/[\/]{2,}i$/i" => "/",
        "/\\\/" => "",
        "/[\/]{2,}/" => "/",
        "/\/$/" => "",
    );
    echo preg_replace(array_keys($patterns),$patterns,$string);

    //OR, this:
    echo    "\n";

    $string = "/^bla\/bla\/bla\//i";
    $pattern = "/(?![\/\w]$)([\w]+)/";
    preg_match_all($pattern,$string,$matches);
    echo join('/',$matches[0]);
?>
Some individuals may disagree with splitting up regex into pieces of logical operations as in the first example, that's a style choice. Still, the bottom method is prefered I would think, better to capture what you do want, than to bother replacing what you don't want.
+1  A: 

I'm not sure if this answers your question, but are you maybe looking for the preg_quote ( http://us.php.net/manual/en/function.preg-quote.php ) function ?

Dominik
A: 

I guess this is not really possible in the context I was thinking of. Thanks for your responses

Petah