【发布时间】:2012-06-19 23:35:58
【问题描述】:
假设在 PHP 中我有一个字符串变量:"This takes between 5 and 7 days"
我需要以整数形式存储一些有关所需时间的合理信息。
如果结果是 5,我很满意。
我尝试去除非数字字符,但结果是 57。
如何以更好的方式做到这一点?
【问题讨论】:
标签: php string type-conversion
假设在 PHP 中我有一个字符串变量:"This takes between 5 and 7 days"
我需要以整数形式存储一些有关所需时间的合理信息。
如果结果是 5,我很满意。
我尝试去除非数字字符,但结果是 57。
如何以更好的方式做到这一点?
【问题讨论】:
标签: php string type-conversion
使用preg_match 使用正则表达式匹配第一个数字组:
$subject = 'This takes between 5 and 7 days';
if (preg_match('/\d+/', $subject, $matches)) {
echo 'First number is: ' . $matches[0];
} else {
echo 'No number found';
}
使用preg_match_all,您可以匹配所有数字组(本例中为5 和7):
$subject = 'This takes between 5 and 7 days';
if (preg_match_all('/\d+/', $subject, $matches)) {
echo 'Matches found:<br />';
print_r($matches);
} else {
echo 'No number found';
}
【讨论】:
/\d+/ 可能会更好,如果可以使用多于一位的数字。
如果你想适当地量化这些数字,我建议如下:
<?php
$subject = "This takes between 5 and 7 days";
$dayspattern = '/\d+(\.\d+)? ?days?/';
$hourspattern = '/\d+(\.\d+)? ?hours?/'
$hours = -1;
if (preg_match($dayspattern , $subject, $matches) > 0)
{
preg_match($dayspattern, $matches[0], $days);
$hours = $days * 24;
} elseif (preg_match($dayspattern , $subject, $matches) > 0) {
preg_match($hourspattern, $matches[0], $hours);
$hours = $hours;
}
?>
您需要考虑:
希望这可以为您提供足够的信息,让您自己完成剩下的工作。
【讨论】:
如果您想提取价格,即 7.50 欧元或 50 美元等 这是正则表达式为我提供的解决方案。
preg_match('/\d+\.?\d*/',$price_str,$matches);
echo $matches[0];
结果 7.50 或 50
【讨论】:
通过将字符串拆分为数组将主题拆分为单词。然后,不知何故,我不知道,从数组中取出单词。也许通过在 try-catch 块内循环遍历数组的所有子元素,并尝试将每个元素更改为 int 类型:
for($i=0;$i<$words->length;$i++){
try{
$tempNum = (int)$words[$i];
}catch($ex){
$words->remove($i);
}
}
或者类似的东西。我不知道任何数组方法,但你明白我的意思。不管怎样,$words 数组现在只包含数字。
【讨论】:
(int) $string)会引发异常。此外,这样的方法并不是一个优雅的解决方案:您可以使用正则表达式来做得更好。