PHP中如何提取字符串纯数字?已尝试str_replace无效
提取字符串中的纯数字解决方案
直接用正则表达式替换所有非数字字符是最简便的方案,str_replace没法搞定是因为要替换的非数字字符种类太多,没法逐一指定。
方法1:直接处理转义后的字符串
用preg_replace匹配所有非数字字符(正则元字符\D代表任何非0-9的字符),替换为空字符串即可:
$escapedStr = '<itcc-ci:somevariabletext contextRef=&quot;cntxCorr_i&quot; unitRef=&quot;eur&quot; decimals=&quot;0&quot;&gt;2020265&lt;/itcc-ci:somevariabletext&gt;'; $pureNumber = preg_replace('/\D/', '', $escapedStr); echo $pureNumber; // 输出:2020265
方法2:先解码HTML实体再提取
如果需要先还原原始HTML结构再处理,可先用htmlspecialchars_decode解码,再做同样的正则替换:
$escapedStr = '<itcc-ci:somevariabletext contextRef=&quot;cntxCorr_i&quot; unitRef=&quot;eur&quot; decimals=&quot;0&quot;&gt;2020265&lt;/itcc-ci:somevariabletext&gt;'; $originalStr = htmlspecialchars_decode($escapedStr); $pureNumber = preg_replace('/\D/', '', $originalStr); echo $pureNumber; // 同样输出:2020265
两种方法都能得到你要的结果,第一种更直接,不需要额外的解码步骤。
内容的提问来源于stack exchange,提问作者Federico
相关产品推荐
相关产品推荐

