Search code examples
phpstringstrpos

Find part of a string and output the whole string


I would like to find part of a string and if true I want to ouput the whole of the string that it finds.

Below is an example:

$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";

if(strstr($Find, $Towns)){
    echo outputWholeString($Find, $Towns); // Result: Eccleston.
}

If anyone can shed some light on how to do this as well, and bare in mind that it will not be static values; the $Towns and $Find variables will be dynamically assigned on my live script.


Solution

  • Use explode() and strpos() as

    $Towns = "Eccleston, Aberdeen, Glasgow";
    $data=explode(",",$Towns);// 
    $Find = "Eccle";
    foreach ($data as $town)
    if (strpos($town, $Find) !== false) {
        echo $town;
    }
    

    DEMO