Regular expression to remove start and end characters from a string?

Let's say I have a line like:

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

I want to use preg_replace () to remove the prefix widget-and remove the suffix .php. Can one regex be used to achieve all this?

The resulting string should be widget-newsletter.

+3
source share
5 answers
$file = preg_replace('/^widget-|\.php$/', '', $file);
+8
source

Why not use substr? Much easier and faster.

+4
source

, , :

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

, "widget-" ".pp" , substr:

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

, , .

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

.

(, -, .):

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

, .

Update:

- _, substr() :

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

:

. , pattern , .

, .

0
source

Source: https://habr.com/ru/post/1747269/


All Articles