如何使用PHP preg_replace替换令牌

I have a string in $body that looks like this:

<td style="vertical-align: top; border: 1px solid gray;">[COMMENT2]</td>

I would like to replace the token [COMMENT2] with the word "None" using something this:

$body = preg_replace('\[.*\]', 'None', $body);

What am I missing?

You should add delimiters / or ~ to your regex like this /\[.*\]/

Php code

<?php
   $body='<td style="vertical-align: top; border: 1px solid gray;">[COMMENT2]</td>';
   $body = preg_replace('/\[.*?\]/', 'None', $body);
   echo $body;
?>

Output:

<td style="vertical-align: top; border: 1px solid gray;">None</td>

Ideone Demo

Regex101 Demo

More about Php delimiters here.

Try this:

$body = '<td style="vertical-align: top; border: 1px solid gray;">[COMMENT2]</td>';
echo $body = preg_replace('/\[[^]]+\]/', 'None', $body);
//=> <td style="vertical-align: top; border: 1px solid gray;">None</td>

RegEx Demo

PHP Demo

May I suggest another approach (with a Parser, that is) ?

<?php
$html = '<html>
            <td style="vertical-align: top; border: 1px solid gray;">[COMMENT2]</td>
        </html>';
$xml = simplexml_load_string($html);

// run an xpath query on the dom
foreach ($xml->xpath("//td[text()='[COMMENT2]']") as &$td)
    $td[0] = 'Some other text';
// just to make sure the html has indeed been changed
echo $xml->asXML();
?>

See a working demo on ideone.com.

I'd suggest with this simple regex:

If you want to replace [...]

$body = preg_replace('%[^>]+(?=</td>)%i', 'None', $body);

If text inside [ and ]

$body = preg_replace('%(?<=\[)[^>]+(?=\]</td>)%i', 'None', $body);

Based on input text

<td style="vertical-align: top; border: 1px solid gray;">[COMMENT2]</td>

It will produce

<td style="vertical-align: top; border: 1px solid gray;">None</td>