ワードプレスのwp_extract_urls関数の使用方法・解説

概要

wp_extract_urls関数は、与えられたテキスト内からすべてのURLを抽出するための便利な関数です。この関数は、ユーザー入力やコンテンツからURLを解析する必要がある場合によく使用されます。具体的には、以下のような機能の実装で役立ちます。

  1. 投稿やページ内のリンクを分析する
  2. ソーシャルシェアボタン用のリンクを抽出する
  3. コンテンツの中の外部リンクをチェックする
  4. ユーザーからの入力に含まれるURLを検証する
  5. リンクの集計やレポート作成
  6. SEO分析のためのURL収集
  7. スパムフィルターによるURLチェック
  8. 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のリンク要素として出力します。

この関数について質問する


上の計算式の答えを入力してください