1

I need to append a text at the end position of the search term.

$baseStr = 'www.abc.com/cdf/?x=10';
$searchStr = 'www.abc.com/';
$insertStr = 'xxx/';

I need to insert $insertStr after 'www.abc.com/' in $baseStr. I get only the start position using strpos.

Expected result:

$resultStr = 'www.abc.com/xxx/cdf/?x=10';

Edit: Is it possible to find the end position of the search string and solve this?

2
  • start of $baseStr is fixed? I mean "www.abc.com"? Commented Apr 25, 2019 at 13:24
  • Possible duplicate of append php form URL Commented Apr 25, 2019 at 13:24

3 Answers 3

2

You can just replace $searchStr with $searchStr plus $insertStr

$baseStr = 'www.abc.com/cdf/?x=10';
$searchStr = 'www.abc.com/';
$insertStr = 'xxx/';
$resultStr = str_replace($searchStr, $searchStr.$insertStr, $baseStr);
echo $resultStr;

gives

www.abc.com/xxx/cdf/?x=10
Sign up to request clarification or add additional context in comments.

Comments

1

Use preg_replace here:

$baseStr = 'www.abc.com/cdf/?x=10';
$searchStr = 'www.abc.com/';
$insertStr = 'xxx/';

$a = preg_replace('#'.$searchStr.'#', $searchStr.$insertStr, $baseStr);
echo '<pre>';
print_r($a);

//Output: www.abc.com/xxx/cdf/?x=10

Or you can use str_replace:

$baseStr = 'www.abc.com/cdf/?x=10';
$searchStr = 'www.abc.com/';
$insertStr = 'xxx/';

$a = str_replace($searchStr, $searchStr.$insertStr, $baseStr);
echo '<pre>';
print_r($a);

//Output: www.abc.com/xxx/cdf/?x=10

Comments

1

You can do something like this,

echo str_replace($searchStr, $searchStr.$insertStr,$baseStr);

Just replace your string it will search and replace for you.

Demo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.