Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find part of a string and output the whole string

Tags:

string

php

strpos

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.

like image 745
Connor Simpson Avatar asked Jun 29 '16 13:06

Connor Simpson


1 Answers

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

like image 177
Saty Avatar answered Nov 11 '22 15:11

Saty