Baptiste Arnaud
Baptiste Arnaud

Reputation: 2760

how to verify that a string contains a character

$string = "#hello";

I'm trying to have hello without the #. I also want a function to verify if the string contains the #.

str_replace("#", " ", $string);

and neither does

strstr($string,"#")

Any ideas ?

Upvotes: 0

Views: 96

Answers (4)

Oisin
Oisin

Reputation: 781

Compare the return value to the original.

if ($string != str_replace("#", "", $string)) 

See: http://php.net/manual/en/function.str-replace.php

Upvotes: 6

Don't Panic
Don't Panic

Reputation: 41820

You don't need to check if the string contains the character you're looking for in order to use str_replace. If the searched character isn't found, str_replace will just return your string unmodified.

If you need to see whether or not '#' was found after the fact, you can use the optional fourth parameter to str_replace that counts the number of replacements:

$string = str_replace('#', '', $string, $count);

Any number of replacements greater than zero will make the $count variable evaluate to boolean true, so you can check if replacements were made just by using if($count)...

if ($count) {
    echo "Replaced $count #s";
    // do whatever you need to do if the string has #
} else {
    echo 'No #s were found.';
}

Upvotes: 2

Jay Blanchard
Jay Blanchard

Reputation: 34426

I'd go with something short, like this:

echo strstr($string, '#') != false ? $string = str_replace("#", "", $string) : $string;

strstr() has to be tested in order to determine whether or not you can make a change.

Upvotes: 0

Ravinder Reddy
Ravinder Reddy

Reputation: 3879

Check the below code:

$string = "#hello";
$find = '#';
// verify if the string contains the #
$pos = strpos($string, $find);
// if present replace it
if ($pos !== false) {
    $string = str_replace("#", "", $string);
}
echo $string;

Output : hello

Upvotes: 2

Related Questions