概要
wp_extract_urls
関数は、与えられたテキスト内からすべてのURLを抽出するための便利な関数です。この関数は、ユーザー入力やコンテンツからURLを解析する必要がある場合によく使用されます。具体的には、以下のような機能の実装で役立ちます。
- 投稿やページ内のリンクを分析する
- ソーシャルシェアボタン用のリンクを抽出する
- コンテンツの中の外部リンクをチェックする
- ユーザーからの入力に含まれるURLを検証する
- リンクの集計やレポート作成
- SEO分析のためのURL収集
- スパムフィルターによるURLチェック
- URLの自動リンク化機能
構文
array wp_extract_urls( string $string )
パラメータ
$string
(string): URLを抽出する元となるテキスト。
戻り値
- (array): 抽出されたURLの配列。
関連する関数
使用可能バージョン
- WordPress 3.3以降。
コアファイルのパス
wp-includes/formatting.php
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプルコード1: URLを抽出する基本的な使い方
$text = "Check out these links: https://example.com and http://test.com.";
$urls = wp_extract_urls($text);
print_r($urls);
このコードは、指定されたテキストからURLを抽出し、結果を表示します。
サンプルコード2: 複数のURLを抽出
$text = "Visit our site at http://example.com. Also see https://another-example.com.";
$urls = wp_extract_urls($text);
foreach ($urls as $url) {
echo $url . "n";
}
このサンプルは、複数のURLを抽出し、それぞれを新しい行に出力します。
サンプルコード3: テキストが含まれる変数からURLを抽出
$input_string = "Here are some links: https://site1.com, http://site2.com and https://site3.com.";
$found_urls = wp_extract_urls($input_string);
if (!empty($found_urls)) {
echo "Found URLs:n" . implode("n", $found_urls);
}
ここでは、変数からURLを抽出し、見つかったURLをリストとして出力します。
サンプルコード4: URLが含まれていない場合のチェック
$text = "No links here!";
$urls = wp_extract_urls($text);
if (empty($urls)) {
echo "No URLs found.";
}
このコードは、テキスト内にURLが存在しない場合の処理を示しています。
サンプルコード5: 抽出したURLをHTMLリンクとして表示
$text = "Links: https://example.com and http://example.org.";
$urls = wp_extract_urls($text);
foreach ($urls as $url) {
echo '<a href="' . esc_url($url) . '">' . esc_html($url) . '</a><br>';
}
このサンプルは、抽出したURLをHTMLのリンク要素として出力します。