The aim is to remove all starting and ending
from a string. There can be none, one and many
at the start and end, independently in number.
I thought on using preg_replace
with a regex expression. But the following test is not working:
$text = "asd
asd
asd
asd
";
//$text = "
asd
asd
asd
asd
";
$text = preg_replace('/^(\n)*(?!\n)(.*)(?<!\n)(\n)*$/', '$2', $text);
var_dump($text);
With regex101.com the group 2 (see $2
above) is exactly the middle of the string, without starting and ending
.
Questions:
- What is wrong with my PHP code above? Why can't I replace the full text with only the middle part? Should I really remove start/end and not replacing with the middle part?
- When I use the regex expression
/^(\n)*(.*)(\n)*$/
instead of the one given above, do I have any disadvantage? In the regex expression above I try "start with
- any char except
- any char wanted but not end with
- end with
". And in the shorter expression I just list none, one or many
at start and end. But could this be a problem, that e.g. only one of many
at start/end will be replaced and some will not be replaced? Is there a guarantee, that a
will not be part of the (.*)
in the middle?
EDIT with solution
- solution: this basic example would also be possible to solve with the PHP
trim
function. (In my case the preg_replace
had a special reason, so for me this answer from ryszard-czech worked)
- attention: the string
$text
must be with double quotes "
and not with single quotes '
because there is a significant difference in PHP!
question from:
https://stackoverflow.com/questions/65602538/php-regex-remove-all-chars-from-start-and-end 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…