"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Extract Substrings Bounded by Characters in PHP Using Regular Expressions?

How to Extract Substrings Bounded by Characters in PHP Using Regular Expressions?

Published on 2024-11-08
Browse:638

How to Extract Substrings Bounded by Characters in PHP Using Regular Expressions?

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:

  • The first character = to match the equal sign.
  • The (.*?) group, which matches any sequence of characters except newlines. The question mark (?) makes it non-greedy, matching as few characters as possible.
  • The final character ] to match the closing square bracket.

If the pattern is found in the string, the matching substring is stored in the $output array at index 1.

Release Statement This article is reprinted at: 1729206975 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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