substr() vs preg_match() using PHP

Greetings fellow developers, I hope you’ve continued to immerse yourself in something interesting whether it’s programming, physics, math – or whatever. The point is – just keep pushing forward and don’t be afraid to fail. Seriously though, enjoy the journey of making mistakes.

This post is about two functions – PHP’s substr() and preg_match() functions.

The reason why I want to emphasize on these two specific functions is because recently in my consulting work I run into some deep code that required my replacing a subtr() function with a preg_match() function. Now, mind you – finding this required some deep digging, hence the phrase “deep code”.

The snippet of code I was working with looked like the code below:

$string = get_field('popup_slider',false,false);
$arr = substr($string, -6,4);


// Where $string would be pulling some kind of string like this example - [soliloquy id="9008"]

// yeah I was working with a soliloquy plugin (hook)

The issue with this though as I learned is it’s reliability would break if we have an “id” longer than 4 digits or characters. Which was exactly what was happening in this case.

And so the fix this with a more reliable method, I decided to use preg_match() and some regex to capture what I needed. Check out the code below:


preg_match('/id="([0-9]+)"/', $string, $matches);
//print_r($matches);
$arr = $matches[1];

So with using preg_match() we can capture any digits of any length and ensure that they aren’t cut off. We pass the $string function and the third argument would be the result once the first argument (regex) is applied.

I would say that actually finding the issue itself was the more difficult task. And then finding a stable solution required some research. For me preg_match() seems quite stable – I’m curious to find out if there is another optimal solution.

Stay tuned for more nerdy posts – until then, keep immersing yourself.