learningtech
learningtech

Reputation: 33683

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

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.

Upvotes: 5

Views: 7875

Answers (5)

Felix Kling
Felix Kling

Reputation: 816312

$name = preg_replace(array('%^widget-%', '%-%', '%\.php$%'), array('','_',''), $file);

should do it.

Or more general (assuming the prefix goes to the first - and the suffix starts at the last .):

$name = preg_replacearray('%^.*?-%', '%-%', '%\.(?!.*?\.).*?$%'), array('','_',''), $file);

If you provide an array of patterns and an array of replacements to the function, then each pattern gets replaced by the according replacement.

Update:

As you removed the requirement to replace the - by _, substr() is indeed better suited:

$name = substr($file, 7, -4);

Upvotes: 1

Oli
Oli

Reputation: 239810

Don't think of it as stripping off the ends, rather as extracting the middle:

$file = 'widget-widget-newsletter.php';
if (preg_match('/^widget\-(.+)\.php$/i', $file, $matches))
    echo "filename is " . $matches[1][0];

Of course, if "widget-" and ".php" are entirely static and are always going to be there, you could just use substr:

echo "filename is " . substr($file, 7, -4);

That would be much faster but if you pass it garbage, you'll get garbage back.

Upvotes: 3

Don Kirkby
Don Kirkby

Reputation: 56610

From the manual description of the replacement parameter:

The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string.

Sounds like you could use an array with the prefix and suffix patterns in it for the pattern parameter, and just put empty string as the replacement.

Upvotes: 0

Felix
Felix

Reputation: 89566

Why not use substr? Much simpler and faster.

Upvotes: 5

John Kugelman
John Kugelman

Reputation: 361564

$file = preg_replace('/^widget-|\.php$/', '', $file);

Upvotes: 10

Related Questions