Yeah, @Jerry is correct in saying that you can't do this in one replacement as you are trying to replace a particular string with two different items (a space or dash, depending on context). I think Jerry's answer is the best way to go about this, but something else you can do is use preg_replace_callback
. This allows you to evaluate an expression and act on it according to what the match was.
$string = 'my project
test project
this is @ long str!ng with spaces and symbo!s';
$string = preg_replace_callback('/([^A-Z0-9]+|\s+|-+)/i', function($m){$a = '';if(preg_match('/(\s+|-+)/i', $m[1])){$a = '-';}return $a;}, $string);
print $string;
Here is what this means:
/([^A-Z0-9]+|\s+|-+)/i
This looks for any one of your three quantifiers (anything that is not a number or letter, more than one space, more than one hyphen) and if it matches any of them, it passes it along to the function for evaluation.function($m){ ... }
This is the function that will evaluate the matches.$m
will hold the matches that it found.$a = '';
Set a default of an empty string for the replacementif(preg_match('/(\s+|-+)/i', $m[1])){$a = '-';}
If our match (the value stored in$m[1]
) contains multiple spaces or hyphens, then set$a
to a dash instead of an empty string.return $a;
Since this is a function, we will return the value and that value will be plopped into the string wherever it found a match.