Reputation: 177
So I need to filter/replace text in PHP to make sure there are spaces around dashes.
Example: "Shirts-general" needs to become "Shirts - general" but I don't want extra spaces, so "Shirts - general" does change to "Shirts - general"(with 2 spaces on each side of the dash.
There will always be a space or text on each side of the dash.
Right now I am using the following and it works, but takes forever (I am checking about 900,000 variables with this code). When I added this my script went from 4 minutes to 52 minutes.
$myText = preg_replace("/(.)(-)(.)/", "$1 - $3", $myText);
Ideas?
Upvotes: 2
Views: 1802
Reputation: 9172
The following should be faster:
preg_replace("/ ?- ?/", " - ", $txt);
And here's a variant with only one call to str_replace:
str_replace(array(' -', '- ', ' - ', '-'), array('-', '-', '-', ' - '), $txt);
Here's an example of both working: http://codepad.org/zqf4LRVD
I'm too lazy to do the performance comparison, but I would be curious to find out which is faster.
Upvotes: 1
Reputation: 20235
This should be faster: preg_replace( "/\\s*-\\s*/", " - ", $myText );
.
Upvotes: 1
Reputation: 3644
I think that's as quick as you'll get. You can try a double str_replace
$once = str_replace("-", " - ", $content);
$twice = str_replace(" - ", " - ", $once);
this will obviously only work if you're not worried about having double spaces to begin with
Upvotes: 0