a regular expression that removes the part enclosed in a string

Asked 2 years ago, Updated 2 years ago, 105 views

I would like to remove the following string.What kind of regular expression should I write to make it possible?
Please let me know if you know more.

[aiu]

Oh, my God.

php html regular-expression

2022-09-30 21:16

1 Answers

We assume that preg_replace is used to remove it with a regular expression.Also, understand that you want to delete a string that is bounded by [ and ] at the end of the string, and in this case, delete the substring using a regular expression similar to the following:

$input='Aiueo[aiu]';

$regexp='/\[[^\]]*\]$/m';

$output=preg_replace($regexp, '', $input);

If you have some knowledge of regular expressions, this is Snakefoot.

\[[^\]]*\]$

Regular expression visualization

Debuggex Demo

The regular expression configuration begins by searching for a substring starting with [], and continues to match until the [^\]* part finds the ending character, ].Then comes along to match as a substring.Assuming the end of the string from the question, the last $ sets the condition that this substring is at the end of the string, but if the location is uncertain, you will get the expected action by deleting it.

Alternatively, if the string comes in this order, you can split the string with [ without using a regular expression to extract the first element.

$output=array_shift(explode('[',$input)));

Alternatively, preg_match can match and take out the first half you want.

if(preg_match('/^[^\[]*/m', $input, $matches)){
    $output = $matches[0];
}

Try various things to find the right one for you.


2022-09-30 21:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.