-5

i have this array in php

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

i wanted to strip all alphabets and dots in the string remains only number like

$name = array("18","16","17","19");

how do i achieve that can some one please guide me how to do it in PHP language

John Dvorak
  • 26,799
  • 13
  • 69
  • 83
usman
  • 15
  • 4

5 Answers5

2

Try this,use preg_replace

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

DEMO

Dave
  • 3,073
  • 7
  • 20
  • 33
1

You can do it without using Regex by using string replace function (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);
?>

Result:

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

Or, if you want to use Regex, than you can use /\d+/ pattern as like:

<?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);
?>

Result:

Array
(
    [0] => 18
    [1] => 16
    [2] => 17
    [3] => 19
)
devpro
  • 16,184
  • 3
  • 27
  • 38
1

Aside from using str_replace() and preg_replace(), you can use array_map() and filter_val() like so:

$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);

Output:

Array

(

        [0] => 18

        [1] => 16

        [2] => 17

        [3] => 19

)

Rax Weber
  • 3,730
  • 19
  • 30
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);

?>
Siddharth Shukla
  • 1,063
  • 15
  • 14
0

A very simplified and native solution from the house of PHP:

    $name = array("page18.jpg","page16.jpg","page17.jpg","page19.jpg",);
    foreach ($name as $n) {
        $num_arr[] = filter_var($n, FILTER_SANITIZE_NUMBER_INT);
    }

    var_dump($num_arr);
    exit();

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

enjoy fresh air ;)

Muhammad Sheraz
  • 569
  • 6
  • 11