0

重複の可能性:
URL を文字列からリンクに変換する (ただし、それらが html タグの属性にある場合を除く)

PHP 正規表現のヘルプを探しています。

招待制のブログの入力ページを作成しているので、スパマーの心配はありません。人々が簡単に URL を追加できるようにしたいのですが、HTML マークアップを使用して喜んでいただけるのであれば、それも可能にしたいと考えています。

以下の例では、$text 変数に 3 つのリンクが含まれています。最初の2つあたりにタグをつけたいのです<a > ... </a>が、3つ目はすでにタグが付いているのでそのままにしておきたいです。私の正規表現は、最後の 2 つのケースでは機能しますが、最初のケースでは機能しません。

私の正規表現は、[^<a href *?= *?\'\"]「文字列が(または類似の)で始まる場合は一致を作成しないでください<a href='>。しかし、実際にはそうではあり^ません。否定者。

出力を次のように表示したいと思います。

Visit <a ...>http://www.example.com/</a> for more info.

<a ...>http://www.example.com/index.php?q=regex</a>

Here is a <i><a ...>link</a> to visit</i>.

正規表現の書き直しについてご協力いただきありがとうございます。

ジェームズ

<?php
$text = "Visit http://www.example.com/ for more info.

http://www.example.com/index.php?q=regex

Here is a <i><a href='http://www.google.ca/search?q=%22php+regex%22&hl=en'>link</a> to visit</i>.";

// Ignore fully qualified links but detect bare URLs...
$pattern = '/[^<a href *?= *?\'\"](ftp|https?):\/\/[\da-z\.-]+\.[a-z\.]{2,6}[\/\.\?\w\d&%=+-]*\/?/i';

// ... and replace them with links to themselves
$replacement = "<a href='$0'>$0</a>";

$output = preg_replace($pattern, $replacement, $text);

// Change line breaks to <p>...</p>...
$output = str_replace("\n", "", $output);
$output = "<p>".str_replace("\r", "</p><p>", $output)."</p>";

// Allow blank lines
$output = str_replace("<p></p>", "<p>&nbsp;</p>", $output);

// Split the paragraphs logically in the HTML
$output = str_replace("</p><p>", "</p>\r<p>", $output);

echo $output;
?>
4

0 に答える 0