从字符串中移除加号(+)[复制]
This question already has an answer here:
I am trying to use preg_replace()
to remove a plus sign (+
) from my string. I used
$variation = preg_replace('/[^\p{L}\p{N}\s]/u', '', $variation);
But that removed periods (.
) too, which I need it in the string. Is there a way to just remove the plus sign?
</div>
此问题已经存在 这里有一个答案: p>
-
如何使用正则表达式检查加号?
\ r
2 answers
span>
li>
ul>
div>
我正在尝试使用 preg_replace() code>从我的字符串中删除加号(
+ code>)。 我用了 p>
$ variation = preg_replace('/ [^ \ p {L} \ p {N} \ s] / u','',$ variation); \ n code> pre>
但是这也删除了句点(
。 code>),我在字符串中需要它。 有没有办法只删除加号? p> div>
Although the original answer to this question does achieve the intended effect, it is not the most efficient way to do this simple task. As noted in the comments above, the use of str_replace()
is preferred in this case.
$variation = str_replace("+", "", $variation);
ORIGINAL ANSWER:
This works to remove only a plus sign:
$variation = preg_replace(/[+]/, "", $variation);
You can see it work here: http://www.phpliveregex.com/p/1Fb (be sure you select the preg_replace function)
For +$7.99
maybe:
$string = ltrim($string, '+$');
Or if for whatever reason they are at either ends use trim()
.
You really don't need regular expressions, given $value = '+$2.47';
:
$value = (float) strtr($value, [
'$' => '',
'+' => '',
]);
var_dump($value); // double(2.47)
Note the (float)
cast; I assume this may be advantageous seeing as you're working with numeric values.
Alternatively, if you're hell-bent on using preg_replace
then match a negated class:
$value = (float) preg_replace('/[^0-9\.]/', '', $value);
var_dump($value); // double(2.47)
This will replace any non-numeric non-dot (.
) characters.