Is there a PHP function that can extract a phrase between 2 different characters in a string? Something like substr()
;
Example:
$String = "[modid=256]";
$First = "=";
$Second = "]";
$id = substr($string, $First, $Second);
Thus $id
would be 256
Any help would be appreciated :)
php function getBetween($content,$start,$end){ $r = explode($start, $content); if (isset($r[1])){ $r = explode($end, $r[1]); return $r[0]; } return ''; } ?> Example: <? php $content = "Try to find the guy in the middle with this function!"; $start = "Try to find "; $end = " with this function!
To get a substring between two characters:Get the index after the first occurrence of the character. Get the index of the last occurrence of the character. Use the String. slice() method to get a substring between the 2 characters.
The substr() is a built-in function of PHP, which is used to extract a part of a string. The substr() function returns a part of a string specified by the start and length parameter. PHP 4 and above versions support this function.
You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .
use this code
$input = "[modid=256]"; preg_match('~=(.*?)]~', $input, $output); echo $output[1]; // 256
working example http://codepad.viper-7.com/0eD2ns
Use:
<?php
$str = "[modid=256]";
$from = "=";
$to = "]";
echo getStringBetween($str,$from,$to);
function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}
?>
$String = "[modid=256]";
$First = "=";
$Second = "]";
$Firstpos=strpos($String, $First);
$Secondpos=strpos($String, $Second);
$id = substr($String , $Firstpos, $Secondpos);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With