I was looking for some code and started thinking about the most efficient way to trim the string (in this case, the URI) with preg_replace .
First of all, I understand that using preg_replace in the first place can be redundant for this task, that it can be uselessly expensive and that it is better to handle it with PHP-friendly functions like substr . I know it.
However, consider these two different regular expressions:
$uri = '/one/cool/uri'; // Desired result '/one/cool' // Using a back-reference $parent = preg_replace('#(.*)/.*#', "$1", $uri); // Using character class negation $parent = preg_replace('#/[^/]+$#', '', $uri);
By default, I would suggest that in the first case, creating a backlink would be more expensive than not doing it, and so a second example would be preferable. But then I began to wonder if using [^/] in the second example could be more expensive than the corresponding one . in the first example, and if so, how much more?
I prefer the first example in terms of readability, and since we split the hair, I tend to choose it between them (in the end, there is also value for writing readable code there). Maybe just my personal preferences.
Thoughts?
source share