Is there a PHP function that can extract a phrase between 2 different characters in a string? Something like substr()
;
Example:
$String
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));
}
?>
use this code
$input = "[modid=256]";
preg_match('~=(.*?)]~', $input, $output);
echo $output[1]; // 256
working example http://codepad.viper-7.com/0eD2ns
Regular Expression is your friend.
preg_match("/=(\d+)\]/", $String, $matches);
var_dump($matches);
This will match any number, for other values you will have to adapt it.
Try Regular Expression
$String =" [modid=256]";
$result=preg_match_all('/(?<=(=))(\d+)/',$String,$matches);
print_r($matches[0]);
Output
Array ( [0] => 256 )
DEMO
Explanation Here its used the Positive Look behind (?<=)in regular expression eg (?<=foo)bar matches bar when preceded by foo, here (?<=(=))(\d+) we match the (\d+) just after the '=' sign. \d Matches any digit character (0-9). + Matches 1 or more of the preceeding token
(moved from comment because formating is easier here)
might be a lazy approach, but in such cases i usually would first explode my string like this:
$string_array = explode("=",$String);
and in a second step i would get rid of that "]" maybe through rtrim:
$id = rtrim($string_array[1], "]");
...but this will only work if the structure is always exactly the same...
-cheers-
ps: shouldn't it actually be $String = "[modid=256]"; ?
If you don't want to use reqular expresion, use strstr, trim and strrev functions:
// Require PHP 5.3 and higher
$id = trim(strstr(strstr($String, '='), ']', true), '=]');
// Any PHP version
$id = trim(strrev(strstr(strrev((strstr($String, '='))), ']')), '=]');