eregi_replace and Regular Expression Quandry

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • saiena

    eregi_replace and Regular Expression Quandry

    Is there a way in my regular expression syntax to cause alternating
    occurences of the search string to be replaced?

    Here's my code:

    $item[content] = eregi_replace($ search_string, $replace_string ,
    $item[content]);

    This successfully replaces all occurences of $search_string.

    Any way to reaplce every other?


  • Andy Hassall

    #2
    Re: eregi_replace and Regular Expression Quandry

    On Mon, 29 Aug 2005 20:55:46 GMT, "saiena" <saiena@nospam_ thetellingtree. com>
    wrote:
    [color=blue]
    >Is there a way in my regular expression syntax to cause alternating
    >occurences of the search string to be replaced?
    >
    >Here's my code:
    >
    >$item[content] = eregi_replace($ search_string, $replace_string ,
    >$item[content]);
    >
    >This successfully replaces all occurences of $search_string.
    >
    >Any way to reaplce every other?[/color]

    The solutions I can think of all need non-greedy expressions, at which point
    you need to use the PCRE (preg_*) functions - which IMHO is worth switching to
    anyway unless you're really tied to the more basic ereg syntax.

    At which point you can either use a clever expression, or just do it with
    preg_replace_ca llback and a Boolean flag or counter accessed by the callback to
    work out whether it's an odd or even call, and so whether to replace or not.

    --
    Andy Hassall :: andy@andyh.co.u k :: http://www.andyh.co.uk
    http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool

    Comment

    • Csaba Gabor

      #3
      Re: eregi_replace and Regular Expression Quandry

      saiena wrote:[color=blue]
      > Is there a way in my regular expression syntax to cause alternating
      > occurences of the search string to be replaced?
      >
      > $item[content] = eregi_replace($ search_string, $replace_string ,
      > $item[content]);
      >[/color]

      How about using:
      $string = preg_replace("/$search_string( .*?($search_str ing|$))/",
      "$replace_strin g\$1",$string);

      where I wrote $string instead of $item[content] cause I didn't
      like the looks of that content. This assumes your $search_string
      doesn't have unusual characters (in which case you'd need to read up on
      regular expressions and escaping characters).

      Csaba Gabor from New York

      Comment

      Working...