仅从数组中获取数字

时间:2016-10-06 06:37:45

标签: php

我在php中有这个数组

$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);

我想剥去字符串中的所有字母和点只保留像

这样的数字
$name = array("18","16","17","19");

我如何实现这一点可以指导我如何用PHP语言

5 个答案:

答案 0 :(得分:2)

试试这个,使用 preg_replace

$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
foreach($name as $val)
{
    $new_name[] = preg_replace('/\D/', '', $val);
}

<强> DEMO

答案 1 :(得分:1)

您可以使用字符串替换功能(str_replace())而不使用正则表达式来执行此操作:

<?php
$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
$myArra = array();
foreach ($name as $key => $value) {
  $var = str_replace("page", "", $value);
  $var = str_replace(".jpg", "", $var);
  $myArra[] = $var; // store all value without text and .jpg
}
print_r($myArra);
?>

<强>结果:

Array
(
    [0] => 18
    [1] => 16
    [2] => 17
    [3] => 19
)

或者,如果您想使用Regex,则可以使用/\d+/模式:

<?php
$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
$myArra = array();
foreach ($name as $key => $value) {
  preg_match_all('/\d+/', $value, $matches);
  $myArra[] = $matches[0][0];  // store all value without text and .jpg
}
echo "<pre>";
print_r($myArra);
?>

<强>结果:

Array
(
    [0] => 18
    [1] => 16
    [2] => 17
    [3] => 19
)

答案 2 :(得分:1)

除了使用str_replace()preg_replace()之外,您可以使用array_map()filter_val(),如下所示:

$name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
$name = array_map(function($fv) {
    return filter_var($fv, FILTER_SANITIZE_NUMBER_INT);
    }, $name);

print_r($name);
  

输出

     

阵列

     

     

[0] =&gt; 18

     

[1] =&gt; 16

     

[2] =&gt; 17

     

[3] =&gt; 19

     

答案 3 :(得分:0)

<?php 

$name = array ("page18.jpg","page16.jpg","page17.jpg","page19.jpg");

$myarray =array(); 

foreach($name as $key =>$value){

$page_replace= str_replace("page", "",$value); //replace page as a blank

$jpg_replace= str_replace(".jpg","",$page_replace); //replace jpg to blank

$myarray[] =$jpg_replace;//stroing without jpg and page getting resulut as key value pair

}
echo "<pre>";

print_r($myarray);

?>

答案 4 :(得分:0)

来自PHP的非常简化的原生解决方案:

" Here, I use бакло as a shortcut for the list of all cyrillic letters,
" this makes this a small self contained example for the word used in the
" problem desctiption, without having the full list in all lines.
" To get the file I actually have, run
" :%s/бакло/ЖжФфЭэЗзЧчБбАаДдВЬвьЪъЫыСсЕеёНнЮюІіКкМмИиЙйПпЛлОоРрЯяГгТтЦцШшЩщХхУу/g
syn match russianWordOk "[бакло]\+"

syn match russianWordError "[бакло][a-zA-Z0-9_]\+"hs=s+1
syn match russianWordError "[a-zA-Z0-9_]\+[бакло]"he=e-1
syn match russianWordError "[бакло][a-zA-Z0-9_]\+[бакло]"hs=s+1,he=e-1

输出: 数组([0] =&gt; 18 [1] =&gt; 16 [2] =&gt; 17 [3] =&gt; 19)

享受清新的空气;)