Soheil
Soheil

Reputation: 5354

Look for a word in a string PHP

How to check if specific work available in a string? Let's say I have a string like this

wrong=name&pass&email

so I want to check if name, pass or/and email are in the string. I need the answer be in boolean so I can do some stuff in there.

Upvotes: 0

Views: 113

Answers (5)

user849137
user849137

Reputation:

Use strstr()

if (strstr($string,'pass'))
{
    echo"pass is here";
}

Upvotes: 1

connec
connec

Reputation: 7421

From the looks of your example it seems what you actually want to do is parse a query string, e.g. with parse_str:

parse_str($string, $result);
if(isset($result['name']))
  // Do something

However, if the string may be malformed etc. I would suggest using strpos, as unlike strstr and others it doesn't need to create a new string.

// Note the `!==` - strpos may return `0`, meaning the word is there at
// the 0th position, however `0 == false` so the `if` statement would fail
// otherwise.
if(strpos($string, 'email') !== false)
  // Do something

Upvotes: 0

WatsMyName
WatsMyName

Reputation: 4478

<?php
$mystring = 'wrong=name&pass&email';
$findme   = 'name';
$pos = strpos($mystring, $findme);


if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?> 

Upvotes: 2

user399666
user399666

Reputation: 19879

if ( stristr( $string, $string_im_looking_for) ){
     echo 'Yep!';
}

Upvotes: 1

Hass
Hass

Reputation: 1636

You can explode the string first. Something like this;

$arrayOfWords = explode('&', $yourString);

Then you loop through the array and check isset.

Upvotes: 0

Related Questions