简体   繁体   中英

how to loop through php object and replace a string in each property ( variable )

I need to remove these ' & ' characters from each property of a php object

I tried the code below but it's not working...what am I missing?

thanks dudes

foreach($query_item as $key => $value)
{
    $key = str_replace(' & ',' & ',$value);
}

You should refer to $value by reference, and modify it in place:

foreach($query_item as $key => &$value)
{
    $value = str_replace(' & ',' & ',$value);
}

The alternative would be to reference the item within the object using $key:

foreach($query_item as $key => $value)
{
    $query_item->$key = str_replace(' & ',' & ',$value);
}

I'll also point out htmlentities() , while we're on the subject of replacing & with &.

foreach($query_item as $key => &$value)
{
    $query_item[$key] = str_replace(' & ',' & ',$value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM