Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.php > #18866

Re: question about preg_replace

From Mateusz Viste <mateusz@xyz.invalid>
Newsgroups comp.lang.php
Subject Re: question about preg_replace
Date 2022-02-23 16:33 +0100
Organization . . .
Message-ID <sv5k3d$1ee0$1@gioia.aioe.org> (permalink)
References <sv5hv3$h8m$2@gioia.aioe.org>

Show all headers | View raw


On 23 Feb 2022 15:56:35 +0100 alex wrote:
> $ echo center | sed -E 's#(.*)#start-\1-end#'
> start-center-end
> 
> I tried to do the same thing with php, but the result is different
> 
> $ php -r "echo preg_replace('#(.*)#', 'start-\0-end', 'center') .
> PHP_EOL;"
> start-center-endstart--end
> 
> Why?

Looks like the preg matches two times: first your 'center' content, and
then what's left (an empty string). I can think of two ways to avoid
that:

Enforce that what's processed has at least one character:

php -r "echo preg_replace('#.(.*)#', 'start-\0-end', 'center') .PHP_EOL;"

Or make sure the preg consumes the entire line:

php -r "echo preg_replace('#^(.*)$#', 'start-\0-end', 'center') .PHP_EOL;"


Mateusz

Back to comp.lang.php | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

question about preg_replace alex <1j9448a02@lnx159sneakemail.com.invalid> - 2022-02-23 15:56 +0100
  Re: question about preg_replace Mateusz Viste <mateusz@xyz.invalid> - 2022-02-23 16:33 +0100
    Re: question about preg_replace alex <1j9448a02@lnx159sneakemail.com.invalid> - 2022-02-23 16:45 +0100
      Re: question about preg_replace Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2022-02-23 15:49 +0000
        Re: question about preg_replace Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2022-02-23 15:51 +0000
          Re: question about preg_replace alex <1j9448a02@lnx159sneakemail.com.invalid> - 2022-02-23 20:10 +0100
      Re: question about preg_replace Mateusz Viste <mateusz@xyz.invalid> - 2022-02-23 18:06 +0100
        Re: question about preg_replace alex <1j9448a02@lnx159sneakemail.com.invalid> - 2022-02-23 20:14 +0100
  Re: question about preg_replace Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2022-02-23 15:45 +0000
    Re: question about preg_replace alex <1j9448a02@lnx159sneakemail.com.invalid> - 2022-02-23 20:19 +0100
    Re: question about preg_replace Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2022-02-23 21:02 +0000

csiph-web