Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The basic replacement of a string with another you can do with <code>str_replace</code>, you need no regexp at all:</p> <pre><code>$string = str_replace('Tue', 'Wed', $string); </code></pre> <p>If you have a series of strings, for example,</p> <pre><code>$weekdays = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'); </code></pre> <p>To replace every day with the following one, we could first generate the "rotated" array</p> <pre><code>$week_one = $weekdays; $week_one[] = array_shift($week_one); </code></pre> <p>But due to the way <code>str_replace</code> works, <strong>we cannot use str_replace($weekdays, $week_one, $string)</strong> (it would replace Mon with Tue, then <em>that</em> Tue with Wed, then <em>that</em> Wed with Thu... and we'd end with all 'Mon'.</p> <p>So we have to do it in two steps. In the first step we replace all strings with strings that surely aren't in the source set, nor in the target string. For example we replace Mon with {{{1}}}. In the second step we replace {{{1}}} with Tue.</p> <pre><code>$weekdays = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'); $replace = array(); foreach($weekdays as $i =&gt; $day) $replace[] = '{{{'.$i.'}}}'; $string = str_replace($weekdays, $replace, $string); // Then we rotate $replace in the opposite direction. array_unshift($replace, array_pop($replace)); // And we reverse the replace. $string = str_replace($replace, $weekdays, $string); </code></pre> <p>You can use a similar approach to replace only the second occurrence of a weekday in a string with the next weekday.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload