Find String in PHP Ready easy function

meabed 1 Tallied Votes 310 Views Share

Better way to find String in PHP ! instead of substring and other php function , This function takes Start and End , and it will return the String in between in another variable ! you can call it easily :)

LastMitch commented: Thanks for sharing! +12
function findtxt($start,$end,$str,&$var) {
	if(stristr($str,$start) && stristr($str,$end)) {
		$txt_pos_s = strpos($str,$start) + strlen($start);
		$txt_pos_e = strpos($str,$end,$txt_pos_s);
		$txt_length = $txt_pos_e - $txt_pos_s;
		$txt = substr($str,$txt_pos_s,$txt_length);
		$var = $txt;
		return TRUE;
	}
	else {
		return FALSE;
	}
}

//Call the function
$str="Address 1: Cairo 14 Street  </br> Address 2: bla bla bla ";
findtxt('Address 1:','Address 2:',$str,$s1);
// then you can remove the html tags from the result string which is $s1
$s1=strip_tags($s1);
Member Avatar for LastMitch
LastMitch

Better way to find String in PHP ! instead of substring and other php function , This function takes Start and End , and it will return the String in between in another variable ! you can call it easily :)

I actually like this code snippet because it is simple and easily understand how strings function work. Thanks for sharing!

I attached an image of the results:

cabc79255bcde945be72bb7ca6d745b1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.