get_url_in_content()
Extracts and returns the first URL found in the given string.
The function scans the given text for links: it looks for a URL in the href attribute of the HTML <a> tag.
It searches only for the first link. If there are several in the text, the others will be ignored.
Before returning, the URL is cleaned using sanitize_url() for security.
Uses: sanitize_url()
No Hooks.
Returns
String|false.
string— The found URL.false— If no URL is found in the content.
Usage
get_url_in_content( $content );
- $content(string) (required)
- The string in which to find a link and extract the URL from.
Examples
#1 Check for absence of URL
If there are no links in the text, the function will return false.
$content = 'This is just text without any links.';
$url = get_url_in_content( $content );
if ( ! $url ) {
echo 'No links found in the text.';
}
// Output: No links found in the text. #2 Demo
In this example we get the first link from a regular string.
$text = ' Visit our main site https://example.com and our blog <a href="https://blog.example.com">blog.example.com</a>. '; $url = get_url_in_content( $text ); //> https://blog.example.com
Changelog
| Since 3.6.0 | Introduced. |
get_url_in_content() get url in content code WP 6.8.3
function get_url_in_content( $content ) {
if ( empty( $content ) ) {
return false;
}
if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
return sanitize_url( $matches[2] );
}
return false;
}