Mayron
Mayron

Reputation: 2394

Split string on last occurrence of an underscore

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?

Upvotes: 2

Views: 114

Answers (1)

user2705585
user2705585

Reputation:

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

Upvotes: 1

Related Questions