JeffCoderr
JeffCoderr

Reputation: 267

If string is within another string

Ok, so I am trying to detect whether a certain string is within another string, I have already tried using explode but it didn't work for obvious reasons, just so you can possibly get a better idea of what I am trying to accomplish, take a look at my failed attempt at using explode to try and solve my question

$stringExample1 = "hi, this is a example";

$stringExample2 = "hello again, hi, this is a example, hello again";

$expString = explode($stringExample1, $stringExample2);

if(isset($expString[1]))
{
    //$stringExample1 is within $stringExample2 !!
}
else
{
    //$stringExample1 is not within $stringExample2 :(
}

Any help will be appreciated thanks

Upvotes: 0

Views: 55

Answers (3)

Samundra
Samundra

Reputation: 1907

Here strpos and strstr fails since you have extra comma in example2 in second string. We can do the string match with regular expression. See the below code snippet for example.

<?php
$str1 = "hi, this is a example";
$str2 = "hello again, hi, this is a example, hello again";
$pattern = "/$str1/";

preg_match_all($pattern, $str2, $matches);

print_r($matches);

output will be

Array
(
    [0] => Array
        (
            [0] => hi, this is a example
        )

)

If count of output array ($matches) is greater than 0 then we have the match otherwise we don't have the match. You might need to tweak the regular expression created in $pattern to suit your need and may also need optimization.

Let us know if this works for you or not.

Upvotes: 2

Dev. Joel
Dev. Joel

Reputation: 1147

You can use strpos

if (strpos($stringExample2 , $stringExample1 ) !== false) {
  echo 'true';
}

or

strstr

if (strlen(strstr($stringExample2,$stringExample1))>0) {
    echo 'true';
}
else
{
    echo 'false';
}

Upvotes: 1

rokas
rokas

Reputation: 1591

Try strpos

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
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: 1

Related Questions