Jump to content

Check for single or double quotes in a string


rv20

Recommended Posts

How do i check a string to see if it contains single or double quotes.

 

I think this fucntion checks if it is alpha numeric which i don't want i just want to check for ' and "  jsut incase you answer with the followng function,

 

if (preg_match('/[^a-z0-9]/i', $username)) {
    return false;//quitting a function
    die('invalid characters');//quit execution
}  

Hi rv20

 

REGEX isn't my strong point, but try this for stripping out single and double quotes from your string

 

$stripped_string = preg_replace('/\'\"/', '', $original_string);

 

(the middle parameter is two single quotes, not one double one)

 

if ($stripped_string ==  $original_string) {    // then there can't have been any quotes in the first place ...

 

Maybe someone better than me at regular expressions can advise as to whether or not I got that first expression right.

What about:

 

<?php

if(strpos("'", $str) > 0 OR strpos('"', $str) > 0){
  // contains either " or '
}

?>

 

Doesn't work, doesn't detect anything, i don't want to strip out the ' or " i want to detect if the input contains them and i can the send a reply back saying invalid username etc..

  • 3 years later...

Due to the type autocasting rules, I'm afraid neither would work.

php > var_dump (false >= 0);
bool(true)
The proper test would read like this. As you'll have to check for type as well, and not just equality:

if (strpos ($value, '"') !== false || strpos ($value, "'") !== false) {
    return true;
}

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.