1

誰でも私がこれを達成する方法を知っています:

投稿メッセージと「*」タグの間のすべてを色付けしたい。このような:

This [*]is[*] test [*]message[*] :)

に:

This [yellow]is[/yellow]> test [yellow]message[/yellow] :)

私は自分の目標を達成するために次のようなものを書きました:

if(preg_match_all('/\*(.*?)\*/',$message,$match)) {  
    $beforemessage = explode("*", $message, 2);      
    $message = $beforemessage[0]. " <font color='yellow'>" .$match[0][0].   "</font>";           
}

ただし、以下のみが返されます。

This [yellow]is[yellow]
4

3 に答える 3

4

preg_replace()を使用するだけです:

$message = "This *is* test *message*";
echo preg_replace('/\*(.*?)\*/', '<font color="yellow">$1</font>', $message);

This <font color="yellow">is</font> test <font color="yellow">message</font>

preg_match_all は一致の配列を返しますが、コードはその配列の最初の一致のみを置き換えます。OTHER の一致を処理するには、配列をループする必要があります。

于 2013-07-30T16:14:55.743 に答える
0

これ、または同様のアプローチを試してください:

<?php

$text = "Hello hello *bold* foo foo *fat* foo boo *think* end.";

$tagOpen = false;

function replaceAsterisk($matches) {
    global $tagOpen;

    $repl = "";

    if($tagOpen) {
        $repl = "</b>";
    } else {
        $repl = "<b>";
    }

    $tagOpen = !$tagOpen;

    return $repl;
}

$result =  preg_replace_callback( "/[*]/", "replaceAsterisk", $text);

echo $result;
于 2013-07-30T16:20:15.777 に答える
0

正規表現を使用する場合、いくつかのアプローチがあります。

1 つはマッチングを行うことです。マッチの位置とマッチの長さを追跡します。次に、元のメッセージを部分文字列に分割し、すべてを連結して戻すことができます。

もう 1 つは、正規表現を使用して検索/置換を行うことです。

于 2013-07-30T16:15:29.723 に答える