Targeting a string between two slashes with PHP & Regex

December 16th, 2022

To create a regular expression that targets a string between two forward slashes (/) on either side in PHP, you can use the following pattern:

/\/(.*?)\//

This regular expression uses the preg_match() function in PHP to search for a string that is surrounded by two forward slashes. The .*? part of the pattern matches any character (.) zero or more times (*) in a non-greedy manner (?), meaning that it will match as few characters as possible before the next forward slash. The .*? is then captured by the parentheses (( )), which creates a capture group that can be accessed after the preg_match() function is called.

Here’s an example of how you can use this regular expression to extract the string between the two forward slashes in a given input string:

$input = "/hello/ there /world/";
preg_match('/\/(.*?)\//', $input, $matches);
// The first captured string will be stored in $matches[1]
echo $matches[1];  // Outputs: "hello"

Note that this regular expression will only match the first occurrence of a string between two forward slashes. If you want to match all occurrences of such a string, you can use the preg_match_all() function instead of preg_match().

Comments

Leave a Reply