Asked  8 Months ago    Answers:  5   Viewed   84 times

Can anyone give me a quick summary of the differences please?

To my mind they both do the same thing?




str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f.{2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.


See for yourself:

$string = "foo fighters";
$str_replace = str_replace('foo','bar',$string);
$preg_replace = preg_replace('/f.{2}/','bar',$string);
echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace;

The output is:

str_replace: bar fighters, preg_replace: bar barhters


Wednesday, March 31, 2021
answered 8 Months ago

<? and <?= are called short open tags, and are not always enabled (see the short_open_tag directive) with PHP 5.3 or below (but since PHP 5.4.0, <?= is always available).

Actually, in the php.ini-production file provided with PHP 5.3.0, they are disabled by default:

$ grep 'short_open' php.ini-production
; short_open_tag
short_open_tag = Off

So, using them in an application you want to distribute might not be a good idea: your application will not work if they are not enabled.

<?php, on the other side, cannot be disabled -- so, it's safest to use this one, even if it is longer to write.

Except the fact that short open tags are not necessarily enabled, I don't think there is much of a difference.

Wednesday, March 31, 2021
answered 8 Months ago

I think this is in the realm of being a micro-optimization. That is, the difference is small enough that it isn't worth using one solution over the other for the sake of performance. If performance were that critical to your app, you wouldn't be using PHP! :-)

Use whatever is more convenient or that makes more sense. I put config data into constants if only because they shouldn't be allowed to change after the config file is loaded, and that's what constants are for.

Wednesday, March 31, 2021
answered 8 Months ago

Can you try this,

    $string ="Hello <%First Name%> <%Last Name%> welcome";
    $Array = array('0' => array ('First Name' => 'John', 'Last Name' => 'Smith' ));
    $Html =$string;
    foreach($datas[1] as $value){           
        $Html =str_replace($value, $Array[0][$value], $Html);
    echo str_replace(array("<%","%>"),'',$Html);
Saturday, May 29, 2021
answered 5 Months ago

You should be good with:

preg_match_all("/b([a-z]+[A-Z]+[a-zA-Z]*|[A-Z]+[a-z]+[a-zA-Z]*)b/", $input, $matches);

Edit: As capturing is not needed, it can be also >>

preg_match_all("/b(?:[a-z]+[A-Z]+[a-zA-Z]*|[A-Z]+[a-z]+[a-zA-Z]*)b/", $input, $matches);
Saturday, May 29, 2021
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :