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

Asked

Viewed 182 times

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 that be varying

  • 2

    you want for example 20 or 2_0

4 answers

4

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

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

  return $matches[1][1];
}

The function preg_match_all has the following parameters:

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

That is, search in $filename the values corresponding to the expression /\d+/ and store them in $matches. After, return the second occurrence (index 1) of the second combination (index 1) of $matches. This way, you get:

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

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


Note: I edited the answer including in the regular expression the character _. 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 analyze 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, what is unlikely to happen.

  • Good answer, besides everything if the names of the files change, but keep the numbers the function will continue working! Congratulations!

1

With regular expressions. No bullshit here goes 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 the image name to be 'banner_x_x_.jpeg or banner_x_x_.jpg'

It returns two variables. Well I did it because it can allow you to do something more if you want. In the $1 variable 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!

0

Explode function: http://php.net/manual/en/function.explode.php Count function: http://php.net/manual/en/function.count.php

roughly, all that is not 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);
?>

-1

A different way using preg_replace:

$string = "banner_2_0_.jpeg";

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

print_r($result); // Result: 0

Looking backwards for one or more numbers followed by underline and period: (\d+)_(\d+)_\..*$/ and complete with the rest of the string to replace everything: /.*_, the $2 is value of the second (\d+) which is the number you need and which will be assigned to the $result.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.