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