RE: [PHP] Replace in a string with regex
| From: | rszeus | Date: | Wed, 22 Jul 2009 23:59:14 +0000 |
| Subject: | RE: [PHP] Replace in a string with regex | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-295722@lists.php.net to get a copy of this message | ||
Thank you very much!
Understand. And it Works very well now.
Cheers
-----Mensagem original-----
De: Ford, Mike [mailto:M.Ford@leedsmet.ac.uk]
Enviada: quinta-feira, 23 de Julho de 2009 00:04
Para: php-general@lists.php.net
Assunto: RE: [PHP] Replace in a string with regex
> -----Original Message-----
> From: rszeus [mailto:rszeus@gmail.com]
> Sent: 22 July 2009 19:23
> To: 'Jim Lucas'
> Cc: 'Kyle Smith'; 'Eddie Drapkin'; ash@ashleysheridan.co.uk; php-
> general@lists.php.net
> Subject: RE: [PHP] Replace in a string with regex
>
> No, sory, my bad typing. It's not the problem..
> I have the same on both caxses, only chnage the variable $id
> $file = "screen/temp/7a45gfdi6icpan1jtb1j99o925_1_mini.jpg"
> $id = '70';
> echo preg_replace('#(screen/)temp/(.+?)_1(.+?\.jpg)#', '$1'.$id,
> $file);
> Get: 0
>
> file = "screen/temp/7a45gfdi6icpan1jtb1j99o925_1_mini.jpg";
> $id = test;
> echo preg_replace('#(screen/)temp/(.+?)_1(.+?\.jpg)#', '$1'.$id,
> $file);
>
> Get: screen/test
>
> What is wrong with having na integer on the var ?
Well, the problem here is that when you concatenate $id containing 70 on to '$1', you
effectively end up with '$170' -- which the manual page at http://php.net/preg-replace makes clear is ambiguous, but is
likely to be treated as $17 followed by a zero, rather than $1 followed by 70. Since $17
doesn't exist (as you don't have that many capturing subpatterns in your pattern!), it is
taken to be the null string -- leaving just the left over 0 as the result of the replacement. QED.
The workaround for this is also given on the page referenced above, which is to make your
replacement be '${1}'.$id.
Incidentally, I don't really see the need for the $1, or the equivalent parentheses in the
pattern -- since a fixed string is involved, why not just use it directly in both places? Like this:
preg_replace('#screen/temp/(.+?)_1(.+?\.jpg)#', 'screen/'.$id, $file);
which completely sidesteps the problem.
Cheers!
Mike
--
Mike Ford,
Electronic Information Developer, Libraries and Learning Innovation,
Leeds Metropolitan University, C507, Civic Quarter Campus,
Woodhouse Lane, LEEDS, LS1 3HE, United Kingdom
Email: m.ford@leedsmet.ac.uk
Tel: +44 113 812 4730
To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm