1

したがって、私の問題は、同じコンテンツにiframe、画像タグなどが含まれていることです。それらはすべて、正しい形式に変換する正規表現の一致を持っています。

最後に残ったのは通常の URL です。iframe、img、またはその他のタグ内ではなく、単にリンクであるすべてのリンクを見つける正規表現が必要です。この場合に使用されるタグは、BB ではなく通常の HTML タグです。

現在、コンテンツ レンダリングの最後のパスとしてこのコードを取得しています。ただし、上記で行われた他のすべてのこと (iframe と img レンダリング) にも反応します。したがって、そこにある URL も交換します。

$output = preg_replace(array(
    '%\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))%s'
), array(
    'test'
), $output);

そして、私のコンテンツは次のようになります。

# dont want these to be touched
<iframe width="640" height="360" src="http://somedomain.com/but-still-its-a-link-to-somewhere/" frameborder="0"></iframe>
<img src="http://someotherdomain.com/here-is-a-img-url.jpg" border="0" />

# and only these converted
http://google.com
http://www.google.com
https://www2.google.com<br />
www.google.com

ご覧のとおり、リンクの最後にも何かがある場合があります。正規表現を機能させるために 1 日を費やした後、最後の作業<br />は私にとって悪夢でした。

4

1 に答える 1

2

説明

このソリューションは、タグ属性値内にない URL に一致し、それらを新しいものに置き換えます。

正規表現は、スキップしたものと置き換えたものの両方に一致します。次に、preg_match_callback は、キャプチャ グループ 1 が入力されているかどうかをテストする内部関数を実行します (これは目的のテキストです)。

未使用のキャプチャ グループを変換するなどのマイナーな変更を加えて、正規表現に一致する URL を使用しました(...)を非キャプチャ グループに(?:... ). これにより、正規表現エンジンの実行が高速になり、式の変更が容易になります。

生の式:<(?:[^'">=]*|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*>|((?:[\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|(?:[^[:punct:]\s]|\/)))

ここに画像の説明を入力

コード

<?php

$string = '# dont want these to be touched
<iframe width="640" height="360" src="http://somedomain.com/but-still-its-a-link-to-somewhere/" frameborder="0"></iframe>
<img src="http://someotherdomain.com/here-is-a-img-url.jpg" border="0" />

# and only these converted
http://google.com
http://www.google.com
https://www2.google.com<br />
www.google.com';


    $regex = '/<(?:[^\'">=]*|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*>|((?:[\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|(?:[^[:punct:]\s]|\/)))/ims';

    $output = preg_replace_callback(
        $regex,
        function ($matches) {
            if (array_key_exists (1, $matches)) {
                return '<a href="' . $matches[1] . '">' . $matches[1] . '<\/a>';
            }
            return $matches[0];
        },
        $string
    );
    echo $output;

出力

# dont want these to be touched
<iframe width="640" height="360" src="http://somedomain.com/but-still-its-a-link-to-somewhere/" frameborder="0"></iframe>
<img src="http://someotherdomain.com/here-is-a-img-url.jpg" border="0" />

# and only these converted
<a href="http://google.com">http://google.com<\/a>
<a href="http://www.google.com">http://www.google.com<\/a>
<a href="https://www2.google.com">https://www2.google.com<\/a><br />
<a href="www.google.com">www.google.com<\/a>
于 2013-07-20T18:29:44.290 に答える