【问题标题】:preg_replace: making regular expressionpreg_replace:制作正则表达式
【发布时间】:2013-09-24 02:43:47
【问题描述】:

我知道有很多关于同一个问题的问题。我阅读了它们,但我无法修复我的代码。

<?
$tabla = "<table>
<tr>
<td>
<a class='texto'>$ 2,123.01</a>
</td>
<td>
asddasdsad$,.$$$
</td>
</tr>
</table>";
echo preg_replace("<a class='texto'>\$ ([0-9]*),([0-9]*).([0-9]*)</a>", "<a class='texto'>$0$1,$2</a>", $tabla);

?>

PHP 错误:警告:preg_replace() [function.preg-replace]: Unknown modifier '$'

我想得到:

<?
<table>
<tr>
<td>
<a class='texto'>2123,01</a>
</td>
<td>
asddasdsad$,.$$$
</td>
</tr>
</table>
?>

我在这里http://regexpal.com/ 尝试并测试了我的正则表达式并且工作正常。但是我在 preg_replace 中有些问题。

【问题讨论】:

  • 你需要/和另一个/在正则表达式的开头和结尾
  • 我试过了,但它打印了原始字符串....

标签: php regex preg-replace


【解决方案1】:

你犯了三个错误:

  1. \$ 双引号内的意思只是 $ 被正则表达式视为与行尾匹配
  2. 您忘记了模式分隔符
  3. $0 指的是整个字符串。括号中的表达式是 称为 1 美元、2 美元等。

echo preg_replace("|<a class='texto'>\\\$ ([0-9]*),([0-9]*).([0-9]*)</a>|", "<a class='texto'>$1$2,$3</a>", $tabla);

【讨论】:

  • 你好@RociioLourdesRodriiguez,欢迎来到 StackOverflow。请考虑accepting您认为对您最有用的答案:)
【解决方案2】:

正则表达式需要在实际表达式周围使用分隔符

<a class='texto'>\$ ([0-9]*),([0-9]*).([0-9]*)</a>

应该是这样的:

/<a class='texto'>\$ ([0-9]*),([0-9]*).([0-9]*)<\/a>/

并转义可能在表达式中的任何其他/

或使用您的表达式中未出现的不同分隔符

#<a class='texto'>\$ ([0-9]*),([0-9]*).([0-9]*)</a>#

List of acceptable delimiters

【讨论】:

  • 我试过了,但它返回了相同的原始字符串。不是预期的结果。
  • 那么你的正则表达式还有其他问题,看看user2755800的回答,他似乎在你的正则表达式中发现了更多错误
猜你喜欢
  • 2011-05-20
  • 2016-07-11
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多