Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to Remove Beginning and End chars from a string?

Tags:

regex

php

Let's say I have a string like so:

$file = 'widget-widget-newsletter.php';

I want to use preg_replace() to remove the prefix widget- and to remove the suffix .php . Is it possible to use one regular expression to achieve all this?

The resulting string should be widget-newsletter.

like image 435
John Avatar asked Dec 02 '22 05:12

John


2 Answers

$file = preg_replace('/^widget-|\.php$/', '', $file);
like image 110
John Kugelman Avatar answered Dec 03 '22 19:12

John Kugelman


Why not use substr? Much simpler and faster.

like image 43
Felix Avatar answered Dec 03 '22 17:12

Felix