-1

我有一个问题,我尝试解决它,但我无法解决它,因为我不熟悉正则表达式,所以我想做的就是转换'A - B''A - C'使用该preg_replace函数。

例如:

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

我该如何使用preg_replace这个问题?

4

3 回答 3

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 回答
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 回答