1

ユーザーが独自の URL を入力できるようにするカスタム編集ユーザー インターフェイスがあり、これまでのところ、URL を見つけてそれらすべてをクリック可能な html リンクに変換する正規表現があります。しかし、StackOverflow の形式と同様に、ユーザーが独自のリンク タイトルを入力するオプションも提供したいと思います。

【リンク名】(http://www.yourlink.com/)

以下のコードを変更して、括弧からタイトルを抽出し、括弧から URL を抽出し、通常の URL をクリック可能なリンクに変換するにはどうすればよいでしょうか (タイトルなしでhttp://www.yourlink.com/と入力しただけでもかまいません)。 )?

$text = preg_replace('/(((f|ht){1}tp:\/\/)[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/i',
                       '<a href="\\1" target="_blank">\\1</a>', $text);
$text = preg_replace('/([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/i',
                       '\\1<a href="http://\\2" target="_blank">\\2</a>', $text);
$text = preg_replace('/([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i',
                       '<a href="mailto:\\1">\\1</a>', $text);
4

2 に答える 2

4

まず、次のように、これらのリンクを説明付きで処理する必要があります。

$text = preg_replace(
    '/\[([^\]]+)\]\((((f|ht){1}tp:\/\/)[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)\)/i',
    '<a href="\\2" target="_blank">\\1</a>', 
    $text
);

しかし今、href に配置された通常の URL は通常のリンクの次の置換反復で一致するため、それを除外するように変更する必要があります。たとえば、前に がない場合のみ一致し"ます。

$text = preg_replace(
    '/(^|[^"])(((f|ht){1}tp:\/\/)[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/i',
    '\\1<a href="\\2" target="_blank">\\2</a>', 
    $text
);
于 2012-11-04T11:03:29.417 に答える
1

これを試して :

<?php
$text = "hello http://example.com sample
[Name of Link](http://www.yourlink.com/)
[Name of a](http://www.world.com/)
[Name of Link](http://www.hello.com/)
<a href=\"http://stackoverflow.com\">hello world</a>
<a href='http://php.net'>php</a>
";
echo nl2br(make_clickable($text));
function make_clickable($text) {
   $text = preg_replace_callback(
    '#\[(.+)\]\((\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|)/))\)#', 
    create_function(
      '$matches',
      'return "<a href=\'{$matches[2]}\'>{$matches[1]}</a>";'
    ),
    $text
  );
  $text = preg_replace_callback('#(?<!href\=[\'"])(https?|ftp|file)://[-A-Za-z0-9+&@\#/%()?=~_|$!:,.;]*[-A-Za-z0-9+&@\#/%()=~_|$]#', create_function(
      '$matches',
      'return "<a href=\'{$matches[0]}\'>{$matches[0]}</a>";'
    ), $text);
  return $text;
}

次のリンクに基づいて作成 (編集) :

テキスト ブロック内のリンクをクリック可能にする最良の方法

正規表現でリンクをクリック可能にする

と ...

于 2012-11-04T11:05:55.670 に答える