If there is a sentence below, please tell me how to write a regular expression that matches anything other than [switch]
.
Hello. [feedback] Good morning.[switch] Thank you.
Note:
I also want to match the [feedback]
of the image.(The method is to match anything other than [switch].
"Take out anything other than the part that matches the regular expression pattern" can be achieved by "removing the part that matches the regular expression pattern."
Use preg_replace
to replace it with an empty character.
<?php
$str='[switch] Hello. [feedback] Good morning.[switch] Thank you.';
$new_str=preg_replace('/\[switch\]/',',',$str);
echo "$new_str\n";
Output:
Hello. [feedback] Good morning.Thank you very much。
Metropolis' comment points out that in this example, the string you want to delete is fixed and [switch]
, so you don't need to use regular expressions.
str_replace
$new_str=str_replace('[switch]',',',$str);
It is sufficient to do so.
If you are going to separate [switch] from the rest, how about the following?
$1 (or \1) and $2 (\2) each contain "Hello [feedback] good morning" and "Thank you very much."
(.*)\[switch\](.*)
I'm sorry if I misunderstood the meaning of the title.
For example,
[switch]
head(?=\[switch\])[switch]
bottom (?<=\[switch\])[switch]
^(.*?)(?=\[switch\])
[switch]
from the bottom to the head of [switch]
(?<=\[switch\])(.*?)(?=\[switch\])
[switch]
from the bottom to the bottom of the string (?<=\[switch\])(.*?)$
Why don't you connect with |
?
(?:^(.*?)(?=\[switch\]))|(?:(?<=\[switch\])(.*?)(?=\[switch\]))|(?:(?<=\[switch\])(.*?)$)
Depending on the situation, adjust it separately as ^$
is appropriate or \A\z
.
Additional information
At the beginning of the string or from the bottom of the [switch]
(?:^|(?<=\[switch\]))
(?:(?=\[switch\])|$)
up to the end of the string or up to the head of the [switch]
It may be simpler to think that
(?:^|(?<=\[switch\]))(.*?)(?:(?=\[switch\])|$)
For your information.
© 2024 OneMinuteCode. All rights reserved.