0

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

1

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer :)
1

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";
}
?>

2 Comments

In my case $findme will include words separated by spaces... Will the use of strpos still work?
@JeffCoderr see my answer and let us know if that is what you are looking for or not. I have tested the both strpos and strstr they didn't work in your case.
1

You can use strpos

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

or

strstr

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.