PHP正则表达式:将文本转换和操作为特定的HTML

时间:2014-07-18 16:51:20

标签: php regex

我有以下文字:

I'm a link - http://google.com

我需要将其转换为以下HTML

<a href="http://google.com">I'm a link</a>

我如何在PHP中实现这一目标?我假设这需要某种正则表达式来搜索实际的文本和链接然后将文本操作到HTML但我不知道从哪里开始,任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:4)

如果它总是这样,那么你真的不需要正则表达式:

$input = "I'm a link - http://google.com";

list($text, $link) = explode(" - ", $input);

echo "<a href='". $link ."'>". $text ."</a>";

答案 1 :(得分:0)

如果需要正则表达式,这里是一个完整的函数代码:

<?php

$content = <<<EOT
test
http://google.com
test
EOT;
$content = preg_replace(
    '/(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/',
    '<a href=\'$0\'>I\'m a link</a>',
    $content
);
echo $content;

?>

此处示例:http://phpfiddle.io/fiddle/1166866001

如果它总是一行文字,那么最好使用1nflktd解决方案。

答案 2 :(得分:0)

尝试捕获组和替换:

^([^-]*) - (.*)$

DEMO

示例代码:

$re = "/^([^-]*) - (.*)$/i";
$str = "I'm a link - http://google.com";
$subst = '<a href="$2"">$1</a>';

$result = preg_replace($re, $subst, $str);

输出:

<a href="http://google.com"">I'm a link</a>

模式说明:

^                        the beginning of the string

  (                        group and capture to \1:
    [^-]*                    any character except: '-' (0 or more times)
  )                        end of \1
   -                       ' - '
  (                        group and capture to \2:
    .*                       any character except \n (0 or more times)
  )                        end of \2

$                        before an optional \n, and the end of the string