Search code examples
phpstringapostrophe

putting a backslash before apostrophe


Which function processes a string putting a backslash before every apostrophes? In other words, I want that

$string="L'isola";
echo somefunction($string);

returns:

L\'isola

Solution

  • You have to use addslashes() method to escape the quote Ex:

    <?php
    $str = "Is your name O'reilly?";
    
    // Outputs: Is your name O\'reilly?
    echo addslashes($str);
    ?> 
    

    and the reverse method is stripslashes() which remove slashes Ex:

    <?php
    $str = "Is your name O\'reilly?";
    
    // Outputs: Is your name O'reilly?
    echo stripslashes($str);
    ?>