Extracting Substrings Bounded by Characters in PHP
Extracting phrases bounded by specific characters from a string is a common programming task. PHP provides a convenient solution for this through regular expressions.
Consider the following string:
$String = "[modid=256]";
To extract the portion between the equal sign (=) and the closing square bracket (]), you can use the following code:
$input = $String;
preg_match('~=(.*?)]~', $input, $output);
echo $output[1]; // 256
In this code, the preg_match() function is used to search for the pattern '=(.*?)]' within the $input string. This pattern consists of:
If the pattern is found in the string, the matching substring is stored in the $output array at index 1.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3