简体   繁体   中英

PHP regex: Converting and manipulating text into specific HTML

I have the following text:

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

I need to convert this into the following HTML

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

How can I achieve this in PHP? I'm assuming this needs some sort of regex to search for the actual text and link then manipulate the text into the HTML but I wouldn't know where to start, any help would be greatly appreciated.

If its always like this, you don't really need regex here:

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

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

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

If a regex is needed, here's a fully function code:

<?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;

?>

Example here: http://phpfiddle.io/fiddle/1166866001

If it's always one line of text though, it would be better to go with 1nflktd solution.

Try with capturing groups and substitution:

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

DEMO

Sample code:

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

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

Output:

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

Pattern Explanation:

^                        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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM