Search code examples
phpquotes

Removing single quotes in PHP


I got some issues trying to INSERT some data from a php document till i got 2 values which contains quotes inside like :

"Rempli d'étoiles"

i d like to remove the ' by a space or even nothing.

-> "Rempli d etoiles" Here is my what i tried :

$posdeapostrophe = strpos($array, '\'');
if ($posdeapostrophe == false) 
{
    ...
}
else
{
    // it goes in this block when it detects a ', but seems like trim doesnt work as i would

    $newchaine =  trim($array, '\'');
    $sql .=  "INSERT INTO categorie (id_cat,name_cat) VALUES (" . $cpt . ",'" .$newchaine . "'); ";

thanks!


Solution

  • You can use str_replace().

    $array = "Some string's";
    $posdeapostrophe = strpos($array, "'");
    $val = '';
    if ($posdeapostrophe !== false)
    {
        $val = str_replace("'", "\'", $array);
    }
    echo $val;
    

    Also can use instead of strpos() and replace() to escape single quotes.

    mysqli_real_escape_string($con, $array ); //for mysqli
    mysql_real_escape_string($array , $con); //for mysql