RE: Replace in a string with regex

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Totally right on the corrections. Sorry, i did not copy paste from the source code, I wrote here to change to other names and wrote it bad.
It should be:
$file = 'screens/temp/7a45gfdi6icpan1jtb1j99o925_1_main.jpg';

 echo $a =  str_replace(array('7a45gfdi6icpan1jtb1j99o925', 'temp/',’_([0-9])’), array('test','',''), $file)

Already understand that str_replace doesn't work with regex, but not getting any luck making one preg_replace() to my needs.

Thank you

-----Mensagem original-----
De: Ashley Sheridan [mailto:ash@xxxxxxxxxxxxxxxxxxxx] 
Enviada: quarta-feira, 22 de Julho de 2009 13:20
Para: rszeus
Cc: php-general@xxxxxxxxxxxxx
Assunto: Re:  Replace in a string with regex

On Wed, 2009-07-22 at 13:02 +0100, rszeus 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
> 
>  
> 
Well, you seem to have some problems with the syntax you're using on
str_replace(). According to your script, you want to remove the
following:

7a45gfdi6icpan1jtb1j99o925    - which you haven't even enclosed in quote
marks
'temp/'
’_([0-9])’        - which are using weird back ticks, not quote marks

and you are trying to replace those three things with

“test”	- again, not proper quote marks
""
””	- not proper quote marks

Afaik, str_replace() doesn't allow for text replacement using regular
expressions, for that you'd have to use something like preg_replace()

Also, make sure your strings are correctly enclosed in quote marks, and
that the quote marks you use are actual quote marks and not the accented
'pretty' ones that are offered up by word processors, etc.

A regex which would do the job would look something like this:

^([^/]+)[^_]+\/(.+)$

That should create 2 matches, one for the initial directory and the
other for the latter part of the filename.

Thanks
Ash
www.ashleysheridan.co.uk


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux