How to match string between two characters using regex.
How to match string between two characters using regex.
449
29-Aug-2023
Updated on 04-Sep-2023
Aryan Kumar
04-Sep-2023Sure, I can help you with that.
To match a string between two characters using regex, you can use the
\bmetacharacter. The\bmetacharacter matches a word boundary. So, if you want to match the string "world" between the characters "w" and "d", you would use the following regex pattern:The
\wmetacharacter matches any word character, which includes letters, numbers, and the underscore character.Here is an example of how to use this regex pattern in PHP:
PHP
This code will output the following:
You can also use the
preg_match_all()function to get all of the matches of the pattern in the string. The syntax for thepreg_match_all()function is as follows:PHP
Where:
patternis the regular expression pattern that you want to match.stringis the string that you want to search.matchesis an array that will contain the results of the match.The
preg_match_all()function will return an array of all of the matches of the pattern in the string.Here is an example of how to use this function:
PHP
This code will output the following:
The
match[0]element of the results array contains the text that was matched by the pattern.