How can I get a specific snippet within a string using PHP?

2

These are my strings:

"banner_2_0_.jpeg",
"banner_2_1_.jpeg",
"banner_2_2_.jpeg", 
"banner_2_3_.jpeg"

I wanted to get the number to be varying

    
asked by anonymous 08.02.2017 / 01:35

4 answers

4

One way to get the value directly without having to work with the return is to use the preg_match_all .

function getNumberFromFilename ($filename): int
{
  preg_match_all("/_(\d+)/", $filename, $matches);

  return $matches[1][1];
}

The preg_match_all function has the following parameters:

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

That is, look at $filename for the values that correspond to the expression /\d+/ and store them in $matches . Then, return the second occurrence (index 1), of the second combination (index 1) of $matches . This way, one has:

> echo getNumberFromFilename("banner_2_0_.jpeg");
0
  

You can see the working code in repl.it with the entire list of files given in the statement.

Note : I have edited the response by including the _ character in the regular expression. In this way, the code will also work for patterns with numeric characters in the first part, such as banner5_2_5.jpeg , because it will only parse the numbers that are preceded by _ . Although there is still the limitation of not being able to have the character _ followed by a number in the first part, such as ban_2ner_3_0.jpeg , which is unlikely to happen.

    
08.02.2017 / 12:13
1

With regular expressions. Without scrolling here is a regular expression:

<?php

(?:banner[\_]([0-9]+)[\_]([0-9]+)[\_][\.](?:jpeg|jpg))

?>

She accepts: banner_2_1_.jpeg or banner_2_1_.jpg

It analyzes and requires that the image name be 'banner_x_x_.jpeg or banner_x_x_.jpg'

It returns two variables. Well I did this because it might allow you to do something else if you want. In variable $ 1 it returns the first number. In variable $ 2 it returns the second number. Now just analyze the variables and do whatever you want. The regex has been tested and anything other than exactly 'banner_xxxxx_xxxx_.jpeg' or 'banner_xxxxx_xxxx_.jpg' is ignored and returns NULL in both variables.

Bye!

    
08.02.2017 / 12:39
0

Function Explode: link Count function: link

In general, everything that is not a banner and .jpg are your numbers.

Soon we could do:

<?php
// Sua variavel
$variavel = "banner_2_0_.jpeg";

// A função explode ele transforma uma string em um arraylist
// ou seja, ao passar o delimitador, ele irá dar um push em 
// toda a palavra que estiver até antes do delimitador, que no
/// nosso caso foi o "_"**/
$array= explode("_",trim($variavel));

// array que receberá somente os numeros
$newArray = array();

// dar um for de acordo com a quantidade de posições
// criadas no array
for($i = 0; $i < count($array); $i++) {

   // como já sabemos que começa com banner e termina com jpeg
   // tudo que não for isso, será nossos numeros
   if ($array[i] !== 'banner' || $array[i] !== '.jpeg')
   {
      // popula o novo array com somente os numeros
      array_push($array[i],$newArray);
   }
}

//imprime o array
print_r($newArray);
?>
    
08.02.2017 / 02:53
-1

A different way using preg_replace :

$string = "banner_2_0_.jpeg";

$result = preg_replace('/.*_(\d+)_(\d+)_\..*$/', "$2", $string);

print_r($result); // Result: 0

I search back and forth for one or more numbers followed by underline and dot: (\d+)_(\d+)_\..*$/ and complete with the rest of the string to be able to replace everything: /.*_ , $2 is value of the second (\d+) that is the number you need that will be assigned to $result .

If you want to join the two numbers you can use: $1$2 instead of just $2 .

    
08.02.2017 / 12:42