如何找到在PHP的字符串是多少? 例如:
<?
$a="Cl4";
?>
我有一个这样的字符串'Cl4'。我想如果在字符串中有一个像'4'的数字给我这个数字,但是如果字符串中没有数字给我1。
如何找到在PHP的字符串是多少? 例如:
<?
$a="Cl4";
?>
我有一个这样的字符串'Cl4'。我想如果在字符串中有一个像'4'的数字给我这个数字,但是如果字符串中没有数字给我1。
$str = 'CI4';
preg_match("/(\d)/",$str,$matches);
echo isset($matches[0]) ? $matches[0] : 1;
$str = 'CIA';
preg_match("/(\d)/",$str,$matches);
echo isset($matches[0]) ? $matches[0] : 1;
<?php
function get_number($input) {
$input = preg_replace('/[^0-9]/', '', $input);
return $input == '' ? '1' : $input;
}
echo get_number('Cl4');
?>
我有另一个问题:D。我想用PHP解决一个方程。例如:'a 2 = b 3'。 我想找到a,b的最慢整数值。你可以帮我吗 ? –
@hassanzanjani,这是另一个问题。 – saji89
$input = "str3ng";
$number = (preg_match("/(\d)/", $input, $matches) ? $matches[0]) : 1; // 3
$input = "str1ng2";
$number = (preg_match_all("/(\d)/", $input, $matches) ? implode($matches) : 1; // 12
下面是一个简单的功能将从您的字符串中提取号码,如果没有找到数字则返回1
<?php
function parse_number($string) {
preg_match("/[0-9]/",$string,$matches);
return isset($matches[0]) ? $matches[0] : 1;
}
$str = 'CI4';
echo parse_number($str);//Output : 4
$str = 'ABCD';
echo parse_number($str); //Output : 1
?>
http://stackoverflow.com/questions/6278296/extract-numbers-from-a-string – jeremy
http://stackoverflow.com/questions/6278296/extract-numbers-from-a-string 这可能有所帮助。 –
@Nile :)几乎在同一时间 –