2

I need to do a search and replace to encapsulate a variable string in single-quotes (php object notation into php array notation) such that the following block:

$my_trip->trip_id = ( $my_trips_opts->trip_id > 0 ) ? $my_trips_opts->trip_id : 1;
$my_trip->trip_name = $my_trips_opts->trip_name;
$my_trip->trip_location_paris = ( $my_trips_opts->trip_location_paris == 'paris' || $my_trips_opts->trip_location_paris == true ) ? true : false;

Is converted to:

$my_trip->trip_id = ( $my_trips_opts['trip_id'] > 0 ) ? $my_trips_opts['trip_id'] : 1;
$my_trip->trip_name = $my_trips_opts['trip_name'];
$my_trip->trip_location_paris = ( $my_trips_opts['trip_location_paris'] == 'paris' || $my_trips_opts['trip_location_paris'] == true ) ? true : false;

The challenge is that the string that follows "$my_trip_opts->" is variable, and likely needs to be stored in a buffer.

3

Not buffers: what you need are tagged regular expressions.

sed "s/\(\$my_trips_opts\)->\([a-zA-Z_]*\>\)/\1['\2']/g"

Basically, in s/patterns/replacement/, if you enclose patterns in escaped brackets, you can refer to them in the replacement by \1, \2 and so on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.