hvs69
asked on
RegEx search for repeating hyphens
I am trying to replace multiple hyphens with a single one. Here is my php code to achive this
I want the $newsting to be "a-b-c-d-e"
However, it does not do anything to the original string. Why is it not working?
<?php
$string = "a--b---c-d-e";
$newstring = preg_replace("/(-)(\1+)/", "-", $string);
?>
I want the $newsting to be "a-b-c-d-e"
However, it does not do anything to the original string. Why is it not working?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ereg_replace("--*", "-", $string)
will replace all multiple instances of - with a single one
will replace all multiple instances of - with a single one
ereg functions are deprecated.
Regarding this, "it does not do anything to the original string." - that is correct, because the new value is assigned to the variable named $newstring.
http://www.laprbass.com/RAY_temp_hvs69.php
Outputs: a-b-c-d-e
Regarding this, "it does not do anything to the original string." - that is correct, because the new value is assigned to the variable named $newstring.
http://www.laprbass.com/RAY_temp_hvs69.php
Outputs: a-b-c-d-e
<?php // RAY_temp_hvs69.php
error_reporting(E_ALL);
// TEST DATA FROM THE POST AT EE
$string = "a--b---c-d-e";
// CONSTRUCT A REGEX
$regex
= '/' // REGEX DELIMITER
. '-+' // MORE THAN ONE HYPHEN
. '/' // REGEX DELIMITER
;
// REPLACE THE HYPHENS WITH ONE HYPHEN
$newstring = preg_replace($regex, '-', $string);
echo $newstring;
<?php
$string = "a--b-- ## -c-d-..e(@)-g";
$newstring = preg_replace("/[^a-z]+/", "-", $string);
echo $newstring;
?>
this will eliminate everything between lowercase letters and puts a single hypen between..
This and @Roads solutions doesn't remove the trailing hypens: if you have
$string = '-a-b-';
it will keep as is. Do you need this too? You can do it in two easy steps (or in one with a more complex regexp)
<?php
$string = "a--b---c-d-e";
$newstring = preg_replace("/[^a-z]+/", " ", $string);
$newstring = preg_replace("/ +/", "-", trim($string));
echo"$newstring";
?>