Re: Find and replace in a string

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

 



On Mon, Jan 27, 2003 at 12:57:10AM +0200, Nikos Gatsis wrote:
>
> Hi list!
> I have a sting that contains some occurances of "{...}" sub-strings, where "...." is some text.
> Which is the way to find and replace the "{...}" with an other of my own.
> This sub-strings start with "{" and end with "}".

You could try something with a regular expression like:

    $new = ereg('[^{]*{([^}]*)}.*', '\\1', $oldstring);

which will match only the first word inside curly braces, or if
$oldstring contains multiple strings in curly braces, maybe:

    $newarray = split('}?[^{]*{', $oldstring . '{');

and then parse the array, and you'll probably want to toss [0], as it
will contain the data before the first left-curly-brace.  This method
needs a trailing left-curly-brace appended to $oldstring because the
regexp relies on it to mark the field.  You could alternately turn this
around as:

    $newarray = split('}[^{]*{?', '}' . $oldstring);

which is probably the cleanest way to do this, given the extent to which
you've described the data so far.  Note that split() will work just fine
on multi-line arrays, including fields split over multiple lines.  If
you want to process your data line-by-line, you'd need to wrap it.

The better you can predict the input data, the cleaner the code you can
use to parse it.

Learn the regexps.

-- 
  Paul Chvostek                                             <paul@it.ca>
  Operations / Abuse / Whatever
  it.canada, hosting and development                   http://www.it.ca/


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


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux