Extract a substring between two characters in a string PHP

Sebastian picture Sebastian · Feb 15, 2013 · Viewed 92.8k times · Source

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 :)

Answer

Yogesh Suthar picture Yogesh Suthar · Feb 15, 2013

use this code

$input = "[modid=256]";
preg_match('~=(.*?)]~', $input, $output);
echo $output[1]; // 256

working example http://codepad.viper-7.com/0eD2ns