Re: Replace in a string with regex
| From: | Jim Lucas | Date: | Wed, 22 Jul 2009 14:54:49 +0000 |
| Subject: | Re: Replace in a string with regex | ||
| References: | 1 2 3 4 5 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-295686@lists.php.net to get a copy of this message | ||
rszeus wrote:
> Thank you.
>
> What about instead test i want to insert a variable ?
> Like
> $id = "30";
> $file = "screens/temp/7a45gfdi6icpan1jtb1j99o925_1_main.jpg";
> echo preg_replace('#(screens/)temp/(.+?)_1(_main\.jpg)#', '$1$id$3',
> $file);
Sure that can be done. But you will need to change the second argument
to have double quotes so it will be parsed by PHP.
Then I would surround YOUR variable with curly brackets to separate it
from the rest.
echo preg_replace('#(screens/)temp/.+?_1(_main\.jpg)#',
"$1{$id}$3",
$file);
> I am confusing " and '.
>
> Thank you
>
>
> -----Mensagem original-----
> De: Eddie Drapkin [mailto:oorza2k5@gmail.com]
> Enviada: quarta-feira, 22 de Julho de 2009 14:12
> Para: rszeus
> Cc: php-general@lists.php.net
> Assunto: Re: [PHP] Replace in a string with regex
>
> On Wed, Jul 22, 2009 at 9:07 AM, rszeus<rszeus@gmail.com> wrote:
>> Hi. It Works to remove the _1 but it doesn't replace
>> '7a45gfdi6icpan1jtb1j99o925' for 'test'
>>
>> Thank you
>>
>> -----Mensagem original-----
>> De: Eddie Drapkin [mailto:oorza2k5@gmail.com]
>> Enviada: quarta-feira, 22 de Julho de 2009 13:11
>> Para: rszeus
>> Cc: php-general@lists.php.net
>> Assunto: Re: [PHP] Replace in a string with regex
>>
>> On Wed, Jul 22, 2009 at 8:02 AM, rszeus<rszeus@gmail.com> wrote:
>>> Hello,
>>>
>>> I’m tryng to make some replacements on a string.
>>>
>>> Everything goês fine until the regular expression.
>>>
>>>
>>>
>>> $file = "screens/temp/7a45gfdi6icpan1jtb1j99o925_1_main.jpg";
>>>
>>> echo $a = str_replace(array(7a45gfdi6icpan1jtb1j99o925,
>>> 'temp/',’_([0-9])’), array(“test”,"",””), $file)
>>>
>>>
>>>
>>> The idea is to remove /temp and the last _1 from the file name..but i’m only
>>> getting this:
>>>
>>> screens/test_1_main.jpg
>>>
>>>
>>>
>>> I want it to be: screens/test_main.jpg
>>>
>>>
>>>
>>> Thank you
>>>
>>>
>>>
>>>
>> If you're trying to do a regular expression based search and replace,
>> you probably ought to use preg_replace instead of str_replace, as
>> str_replace doesn't parse regular expressions.
>>
>> Try this one out, I think I got what you wanted to do:
>>
>> <?php
>>
>> $file = "screens/temp/7a45gfdi6icpan1jtb1j99o925_1_main.jpg";
>>
>> echo preg_replace('#(screens/)temp/(.+?)_1(_main\.jpg)#', '$1$2$3',
>> $file);
>>
>>
>
> In the second parameter, $2 is the string you'd want to replace to
> test so change '$1$2$3' to '$1test$3'.
>
> It seems like you're having trouble with regular expressions, may I
> suggest you read up on them?
>
> http://www.regular-expressions.info/ is a pretty great free
> resource,
> as ridiculous as the design is.
>
>