Question

How to replace words in a sting that starts with@@and ends with @@with some other words? Thanks in advance

$str = 'This is test @@test123@@';

how get the position oftest123and replace with another one

Was it helpful?

Solution 2

Not that you shouldn't necessarily use regular expressions here, but here is an alternative:

Given: $str = 'This is test @@test123@@';

$new_str = substr($str, strpos($str, "@@")+2, (strpos($str, "@@", $start))-(strpos($str, "@@")+2));

Or, same thing broken down:

$start = strpos($str, "@@")+2;
$end = strpos($str, "@@", $start);
$new_str = substr($str, $start, $end-$start);

Output:

echo $new_str; // test123

OTHER TIPS

You're better off with regular expressions.

echo $str = preg_replace("~@@(.*?)@@~","This is the replaced text", $str);

Demonstration

Editing the answer .. As OP asked the question in an unclear context

Since you are looking to grab the content. Use preg_match() and the same regular expression.

<?php
$str = 'This is test @@test123@@';
preg_match("~@@(.*?)@@~", $str, $match);
echo $match[1]; //"prints" test123

This type of template tag replacement is best handled with preg_replace_callback.

$str = 'This is test @@test123@@.  This test contains other tags like @@test321@@.';

$rendered = preg_replace_callback(
    '|@@(.+?)@@|',
    function ($m) {
        return tag_lookup($m[1]);
    },
    $str
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top