-2

How can i change a word on long string(text) in PHP?

Example: Text: stackoverflow site is best site.

1) I want to change first "site" string to "website" but i don't want to change second "site".

2) how can i change second "site" without change first "site"?

3) how can i change all "site"?

Thanks

mgraph
  • 15,238
  • 4
  • 41
  • 75

2 Answers2

2

All occurences

Easiest is to replace all occurrences. Just use str_replace on your string

$str = 'stackoverflow site is best site';
$str = str_replace('site', 'website', $str);

Live example

First occurence

To replace single instances (like the first, or second, or etc), you can use substr_replace which allows you to replace a certain character range with text. You have to find that range first though. You can use strpos for that.

$str = 'stackoverflow site is best site';
$search = 'site';
$start = strpos($str, $search);
$str = substr_replace($str, 'website', $start, strlen($search));

Live example

Any specific occurence

Now extending on the previous code to replace the second or third instances, you need to subsequently call strpos and feed it the offset of the previous result. Here is a simple way to do it with a for loop.

$str = 'stackoverflow site is best site';
$search = 'site';
$count = 2;
$start = strpos($str, $search);
for($i = 0; $i < $count - 1; $i++)
    $start = strpos($str, $search, $start + 1);
$str = substr_replace($str, 'website', $start, strlen($search));

Live example

I am using a $count variable to determine what word I want to replace.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
0

1) Here's how you change first "site":

<?php
$string="stackoverflow site is best site.";
echo "<strong>First:</strong> ".$string;

$string_replace=preg_replace('/site/', 'website', $string, 1);
echo "<br /><strong>After:</strong> ".$string_replace;
?>

2) Here's how you change the last "site":

<?php
$string="stackoverflow site is best site.";
echo "<strong>First:</strong> ".$string;

$pos=strrpos($string, 'site');
$string_replace=substr_replace($string, 'website', $pos, strlen('site'));
echo "<br /><strong>After:</strong> ".$string_replace;
?>

3) Here's how you change all "site":

<?php
$string="stackoverflow site is best site.";
echo "<strong>First:</strong> ".$string;

$string_replace=str_replace("site", "website", $string);
echo "<br /><strong>After:</strong> ".$string_replace;
?>

That will change all "site" to "website".

Robinjoeh
  • 345
  • 3
  • 12
  • You're not saving the return value from `str_replace`, so it's doing nothing. Also, the `count` parameter on `str_replace` is for **how many** replacements were made, not to specify a limit. – nickb Jun 28 '12 at 19:26
  • Your first `str_replace` won't replace the first "site". – flowfree Jun 28 '12 at 19:27