Tags
Asked 3 years ago
1 Jul 2021
Views 300
Margaret

Margaret posted

PHP: find text between href=' tag

PHP: find text between href='' tag
jagdish

jagdish
answered May 4 '23 00:00

To find text between href tags in PHP, you can use a regular expression with the preg_match() function. Here's an example:


$string = '<a href="https://www.example.com">Example</a>';
preg_match('/<a\s+href="([^"]+)">/', $string, $matches);
echo $matches[1];

In the example above, we have a string containing an <a> tag with an href attribute. We use the preg_match() function with a regular expression to extract the URL from the href attribute. The regular expression matches the entire <a> tag and captures the URL using a capture group.

Here's how the regular expression works:

/<a\s+href=" - matches the opening <a> tag and the href attribute
([^"]+) - captures the URL between the quotes of the href attribute
">/ - matches the closing quotes of the href attribute and the end of the opening <a> tag
After running the preg_match() function, the $matches array will contain the captured URL in the second element ($matches[1]). In this case, the code will output https://www.example.com.

You can modify the regular expression to match different patterns and extract different parts of the <a> tag, depending on your needs.

Post Answer