You are here: Re: regexp help please « PHP Programming Language « IT news, forums, messages
Re: regexp help please

Posted by Chung Leong on 11/18/97 11:43

Justin Koivisto wrote:
> Disco Octopus wrote:
> > Hi,
> >
> > I think I am need of a regular expression with regards to a str_replace
> > need that I have...
> >
> > I have a string like this one...
> >
> > "text text text{
> > text
> > } text {text text } t {text} txt { text }"
> >
> > I need to replace all occurances of "{" with "{ " and "}" with " }" where
> > the following rules apply...
> >
> > replace "{" with "{ " when the character to the right of "{" is NOT
> > <newline> and is NOT <space> and is NOT <tab>.
> >
> > replace "}" with " }" when the character to the left of "}" is NOT
> > <newline> and is NOT <space> and is NOT <tab>.
> >
> > So, the result in my example above would be....
> >
> > "text text text{
> > text
> > } text { text text } t { text } txt { text }"
> >
> > Would anyone possibly know how to do this?
>
> You would need to use both a zero-width negative look-ahead and a
> zero-width negative look-behind with prel style regex...
>
> <?php
> $s =<<<EOS
> text text text{
> text
> } text {text text } t {text} txt { text }
> EOS;
>
> $search1='`\{(?![\s\r\n\t])`';
> $replace1='{ ';
> $s=preg_replace($search1,$replace1,$s);
>
> $search2='`(?<![\s\r\n\t])\}`';
> $replace2=' }';
> $s=preg_replace($search2,$replace2,$s);
>
> echo $s;
>
> ?>
>
>
> --
> Justin Koivisto, ZCE - justin@koivi.com
> http://koivi.com

\r, \n, \t are covered by \s already, so there is no need to specify
them separately. The code can be further compacted by using array
arguments to preg_replace():

$search = array('`\{(?!\s)`', '`(?<!\s)\}`');
$replace= array('{ ', ' }');
$s=preg_replace($search,$replace,$s);

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация