-1

'A - B'質問があり解いてみたのですが、正規表現に不慣れで解けなかったので、関数を'A - C'使って変換したいですpreg_replace

例えば:

'Mon ~ Tue' => 'Mon ~ Wed'

preg_replaceこの問題にどのように使用できますか?

4

3 に答える 3

1

The basic replacement of a string with another you can do with str_replace, you need no regexp at all:

$string = str_replace('Tue', 'Wed', $string);

If you have a series of strings, for example,

$weekdays = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');

To replace every day with the following one, we could first generate the "rotated" array

$week_one = $weekdays;
$week_one[] = array_shift($week_one);

But due to the way str_replace works, we cannot use str_replace($weekdays, $week_one, $string) (it would replace Mon with Tue, then that Tue with Wed, then that Wed with Thu... and we'd end with all 'Mon'.

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.

$weekdays = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
$replace  = array();
foreach($weekdays as $i => $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);

You can use a similar approach to replace only the second occurrence of a weekday in a string with the next weekday.

于 2012-10-21T22:42:03.403 に答える
1

これには正規表現は必要ありません。

str_replace('Mon ~ Tue', 'Tue', 'Wed');

うまく機能しているようです。

ここで何かが欠けていない限り?

于 2012-10-21T22:23:54.347 に答える
1

The code bellow seems to do the job, but it's hard to guess what exactly are you trying to do.

$x = "Mon ~ Tue"; preg_replace("/(Mon ~ )Tue/", "\$1Wed", $x);

于 2012-10-21T22:25:46.823 に答える