0

テキストとリンクを含む 1 つの文字列に連結された一連の文字列があります。文字列内の URL を検索し、それぞれに配置したいhref(リンクを作成する)。文字列内の URL (リンク) を見つけるために正規表現パターンを使用しています。以下の私の例を確認してください:

例 :

    <?php

// The Text you want to filter for urls
        $text = "The text you want to filter goes here. http://google.com/abc/pqr
2The text you want to filter goes here. http://google.in/abc/pqr
3The text you want to filter goes here. http://google.org/abc/pqr
4The text you want to filter goes here. http://www.google.de/abc/pqr";

// The Regular Expression filter
        $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";


// Check if there is a url in the text
        if (preg_match($reg_exUrl, $text, $url)) {
            // make the urls hyper links
            echo preg_replace($reg_exUrl, "<a href='.$url[0].'>" . $url[0] . "</a> ", $text);
        } else {
            // if no urls in the text just return the text
            echo $text . "<br/>";
        }
        ?>

しかし、次の出力が表示されています。

>  The text you want to filter goes here. **http://google.com/abc/pqr** 2The
> text you want to filter goes here. **http://google.com/abc/pqr** 3The text
> you want to filter goes here. **http://google.com/abc/pqr** 4The text you
> want to filter goes here. **http://google.com/abc/pqr**

これの何が問題なのですか?

4

1 に答える 1

2

正規表現はスラッシュで区切られているため、正規表現にスラッシュが含まれている場合は十分に注意する必要があります。多くの場合、正規表現を区切るために別の文字を使用する方が簡単です。PHP は何を使用してもかまいません。

最初と最後の「/」文字を「#」などの別の文字に置き換えてみると、コードが機能する可能性が高くなります。

次のように、コードを単純化し、preg_replace への 1 回の呼び出しですべてを実行することもできます。

<?php

$text = 'The text you want to filter goes here. http://google.com/abc/pqr
    2The text you want to filter goes here. http://google.in/abc/pqr
    3The text you want to filter goes here. http://google.org/abc/pqr
    4The text you want to filter goes here. http://www.google.de/abc/pqr';

echo preg_replace('#(http|https|ftp|ftps)\://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/\S*)?#i', '<a href="$0">$0</a>', $text);
于 2013-02-09T19:07:34.277 に答える