0

I need to find a way in PHP to remove the last portions of 2 strings using regex's. This way once they are stripped of the extra characters I can find a match between them. Here is an example of the type of string data I am dealing with:

categories_widget-__i__
categories_widget-10

So I would like to remove:

-__i__ from the first string
-10 from the second string

Thanks in advance.

Benjamin
  • 697
  • 1
  • 8
  • 32

4 Answers4

0

You could try the below code to remove all the characters from - upto the last.

<?php
$text = <<<EOD
categories_widget-__i__
categories_widget-10
EOD;
echo preg_replace("~-.*$~m","",$text);
?>

Output:

categories_widget
categories_widget

- matches the literal - symbol. And .* matches any character following the - symbol upto the end of the line. $ denotes the end of a line. By replacing all the matched characters with an empty string would give you the desired output.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0
$str1 = "categories_widget-__i__";
$str2 = "categories_widget-10";
$arr1 = explode("-", $str1);
$arr2 = explode("-", $str2);
echo $arr1[0];
echo $arr2[0];
Clément Malet
  • 5,062
  • 3
  • 29
  • 48
0

Is the last occurrence of a hyphen the only thing that's important? If so you don't need regex:

$firstPart = substr($str, 0, strrpos($str, '-'));

» example

Emissary
  • 9,954
  • 8
  • 54
  • 65
0
(.*)-

This simple regex can do your job if - is the splitting criteria

See demo.

http://regex101.com/r/rX0dM7/7

vks
  • 67,027
  • 10
  • 91
  • 124