查找并替换以某些字符开头的文本中的所有字符串

查找并替换以某些字符开头的文本中的所有字符串

问题描述:

I am attempting to allow users to link to other wallposts within their own wallposts. so for example if user types: Please see post ::35 for more information I would change the string to: Please see <a href="posts/35">35</a> for more information

I have the following function which grabs all the post numbers from the content, as denoted by :: at the beginning.

function getBetween($content, $start, $end, $rest = array()) {
    $r = explode($start, $content, 2);
    if (isset($r[1])) {
        $r = explode($end, $r[1], 2);
        $rest[] = $r[0];
        return getBetween($r[1], $start, $end, $rest);
    } else {
        return $rest;
    }
}

$post = 'Lorem ::35 ipsum ::36 dolor sit ::37 ::38';
$links = getBetween($post, '##', ' ');

$links returns an array containing 35, 36, 37, 38. What I don't know is how I can replace them in the original string with the hyperlinks.

This code will find ::digit that is flanked by white space or appears at the start or end of the text.

$post = 'Lorem ::35 ipsum ::36 dolor sit ::37 ::38';
$post = preg_replace('/(\G|\s+|^)::(\d+)((?=\s+)|(?=::)|$)/','$1 <a href="?postid=$2">$2</a> $3',$post);
echo $post;

// Lorem <a href="?postid=35">35</a> ipsum <a href="?postid=36">36</a> dolor sit <a href="?postid=37">37</a> <a href="?postid=38">38</a>

If your link to posts is something like

http://example.com/post/POSTID

or

http://example.com/viewpost.php?postid=POSTID

You may use preg_replace to replace it at once, like

$result = preg_replace('/::(\d+)/', 'http://example.com/viewpost.php?postid=$1', $content)