重複の可能性:
文字列から数字を抽出する
PHPで文字列内の数値を見つけるにはどうすればよいですか? 例えば :
<?
$a="Cl4";
?>
この 'Cl4' のような文字列があります。文字列に「4」のような数字がある場合はこの数字を返しますが、文字列に数字がない場合は 1 を返します。
重複の可能性:
文字列から数字を抽出する
PHPで文字列内の数値を見つけるにはどうすればよいですか? 例えば :
<?
$a="Cl4";
?>
この 'Cl4' のような文字列があります。文字列に「4」のような数字がある場合はこの数字を返しますが、文字列に数字がない場合は 1 を返します。
<?php
function get_number($input) {
$input = preg_replace('/[^0-9]/', '', $input);
return $input == '' ? '1' : $input;
}
echo get_number('Cl4');
?>
これは、文字列から数値を抽出する単純な関数であり、数値が見つからない場合は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
?>
$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;
$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