2

I need to extract from a string 2 parts and place them inside an array.

$test = "add_image_1";

I need to make sure that this string starts with "add_image" and ends with "_1" but only store the number part at the very end. I would like to use preg_split as a learning experience as I will need to use it in the future.

I don't know how to use this function to find an exact word (I tried using "\b" and failed) so I've used "\w+" instead:

$result = preg_split("/(?=\w+)_(?=\d)/", $test);
print_r($result);

This works fine except it also accepts a bunch of other invalid formats such as: "add_image_1_2323". I need to make sure it only accepts this format. The last digit can be larger than 1 digit long.

Result should be:

Array ( 

    [0] => add_image 

    [1] => 1 

)

How can I make this more secure?

Mayron
  • 2,146
  • 4
  • 25
  • 51

1 Answers1

1

Following regex checks for add_image as beginning of string and matches _before digit.

Regex: (?<=add_image)_(?=\d+$)

Explanation:

  • (?<=add_image) looks behind for add_image

  • (?=\d+$) looks ahead for number which is end of string and matches the _.

Regex101 Demo

  • ah so that's how you look for exact words, thanks! I was using it all wrong. – Mayron Mar 12 '16 at 22:40
  • @Mayron: Yes ! you were using `\w+` which means anything in the character class `[A-Za-z0-9_]` repeated several times. –  Mar 12 '16 at 22:42
  • Besides that I made sure that once a number is encountered after `_` there is not other `character` by marking it end of string by `$`. So patterns like `add_image_1_23`, `add_image_9sd` would not be matched at all. –  Mar 12 '16 at 22:44
  • I tried using parenthesis around (add_image) but that didn't work. I also tried using "\b" because I heard that was for capturing full sub-strings. But only your method worked. – Mayron Mar 12 '16 at 22:48
  • 1
    `\b` is boundary check. It checks for word boundaries. Read more about it [here](http://www.regular-expressions.info/wordboundaries.html). –  Mar 12 '16 at 22:51
  • 1
    Thank you! Appreciate it :) – Mayron Mar 12 '16 at 22:56