/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] preg_replace versus str_replace

Why do I keep seeing:

$url = preg_replace(“/s/e” , “_” , $url);

when it seems simpler to do:

$url = str_replace(” ” , “_” , $url);

Do they really do the same thing? which is faster? whats the e for?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@andre4s_yJun 05.2008 — They do not do the same thing...

this code show you the difference between them :
[code=php]
<?php
$test = "This is a test,n for test purpose only ...";
$url = preg_replace("/s/" , "_" , $test);
//preg_replace with pattern without e modifier
echo $url;

$url = str_replace(" " , "_" , $test);
echo $url;
?>
[/code]

Guest what?? Where is the difference?

Right...

pattern s in regex means horizontal and vertical space. So, this pattern will match n and will replace it with char _.

Str_replace can not recognize it...

Which is faster? I do not test them... But i think str_replace is faster since preg_replace do more... ?
Copy linkTweet thisAlerts:
@NogDogJun 05.2008 — Yes, str_replace() will be faster in simple situations where it can do the same thing as preg_replace() is a single command. preg_replace()'s ability to use regular expressions will however probably be more efficient in cases where you would have to use multiple calls to str_replace() to accomplish the same thing.

In this case, however, I'm not sure which would be more efficient (nor would I really care 99.99% of the time) since you could do it in one str_replace() by using an array:
[code=php]
$string = str_replace(array(' ', "n", "r", "t"), '_', $string);
[/code]
Copy linkTweet thisAlerts:
@curtayauthorJun 05.2008 — Thanks. works great
×

Success!

Help @curtay spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...