How can you capture and return the matched word in a string using regular expressions in PHP?
To capture and return the matched word in a string using regular expressions in PHP, you can use the `preg_match()` function. This function searches a string for a pattern and returns true if the pattern is found, and false otherwise. To capture the matched word, you can use parentheses `()` in the regular expression pattern to create a capturing group. The matched word can then be accessed using the `$matches` array.
$string = "The quick brown fox jumps over the lazy dog";
$pattern = '/\b(brown)\b/';
if (preg_match($pattern, $string, $matches)) {
echo "Matched word: " . $matches[1];
} else {
echo "No match found";
}
Keywords
Related Questions
- In cases where changing the encoding to UTF-8 does not resolve special character display issues, what alternative methods or functions in PHP can be used to handle character encoding discrepancies?
- How can PHP developers ensure that array elements are inserted correctly in a multi-dimensional array?
- What are potential issues with the provided PHP code for pagination?