preg_replace未定义变量错误
我试图从字符串中删除货币符号,但出现“未定义变量”错误。抱歉,如果这完全是愚蠢的,我是新手!
<? if ($event->ticket_cost) : ?>
<? $cost = $event->ticket_cost ?>
<? $cost = preg_replace("€£$","", $cost) ?>
<?=$cost ?>
<? else : ?>
<? echo '' ?>
<? endif ?>
谢谢!
I'm trying to remove currency symbols from a string, but getting an 'undefined variable' error. Sorry if this is totally dumb, I'm a newbie!
<? if ($event->ticket_cost) : ?>
<? $cost = $event->ticket_cost ?>
<? $cost = preg_replace("€£$","", $cost) ?>
<?=$cost ?>
<? else : ?>
<? echo '' ?>
<? endif ?>
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用分隔符:
此外,由于
$
是正则表达式中的特殊字符,因此您需要像上面一样用反斜杠对其进行转义。另外,您正在使用
,它应该是
或更好的
除非您没有使用任何其他专门的设置或东西。
You need to use delimitters:
Also since
$
is special character in regex, you need to escape it with backslash like above.Also you are using
<?
, it should be<?=
or better<?php
unless you are not using any other specialized setting or stuff.你有三件事错了:
"~€£$~"
)$
是 php 中的变量统计名称(也在双引号中计算),因此可以使用\< 对其进行转义/代码>:
"~€£\$~"
或使用'
(单引号)'~€£$~'
$
是 PCRE 表达式中的 元字符,负责行尾它必须被转义,所以最终的正则表达式将如下所示:"~€£\\\$~"
或:'~€£\\$~'
还有一件事,为什么你不使用“哑字符串替换” “(例如
strtr()
)应该拥有更好的性能,它会让你更清楚你想要做什么,例如:AFAIK
str_replace()
会迭代字符串 3 次,strtr()
只会迭代一次。You have three things wrong:
"~€£$~"
)$
is variable stat name in php (evaluted in double quotes too), so either escape it with\
:"~€£\$~"
or use'
(single quot)'~€£$~'
$
is meta character in PCRE expressions responsible for end of line therefor it must be escaped so final regexp would look like:"~€£\\\$~"
or:'~€£\\$~'
And one more thing, why won't you use "dumb string substitution" (for example
strtr()
) which should have better performance and it'll make more clear what you want to do, example:AFAIK
str_replace()
would iterate trough string 3 times,strtr()
just once.注意:将价格和货币存储在一个字段中并不是一个好主意
note: storing the price and currency in one field is not a good idea