Eg: Lorem ipsum dolor sit amet, [ID: 123] Suspendisse [blahsh 68] condimentu
How would I get 123?
I have the first part where I check the character position:
$pos = strrpos($l, "ID: ");
if ($pos === false) {
$id = 123;
}
This is most easily handled with a regular expression.
$matches = array();
$pattern = '/^.*\[ID:\s+(\d+)\].*$/';
preg_match($pattern, "Lorem ipsum dolor sit amet, [ID: 123] Suspendisse [blahsh 68] condimentu", $matches);
// Your number is in $matches[1]
Array
(
[0] => Lorem ipsum dolor sit amet, [ID: 123] Suspendisse [blahsh 68] condimentu
[1] => 123
)
The pattern matches [ID:
followed by any number of spaces via \\s+
. Then (\\d+)
captures the sequence of digits. The []
brackets need to be escaped as \\[ \\]
because they are meta-characters in the regular expression.
If you are interested in the rest of the expression:
^.*
is the start of the string and anything else following... .*$
is anything else up to the end of the string after the matched section already explained above. Maybe like this if the string is always [ID:1234]
$str='Lorem ipsum dolor sit amet, [ID: 123] Suspendisse [blahsh 68] condimentu';
preg_match_all("~\[ID:\s(.*?\d+)\]~",$str,$match);
echo $match[1][0];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.