替换包含序列化数组的字符串中的文本



感谢您点击问题。我正在尝试查找和替换包含序列化数组的字符串中的文本。例如:

'fgm2wc_options', 'a:19:{s:15:"automatic_empty";N;s:3:"url";s:25:"http://example.com/store/";s:8:"hostname";s:9:"localhost";s:4:"port";s:4:"3306";s:8:"database";s:22:"apgadmin_store_magento";s:8:"username" ... }

我想将 http://example.com/更改为smth,否则我可以用str_replace做到这一点,但它不会更改字符串长度指示器(例如s:25(。

这是我正在使用的功能:

function recursive_unserialize_replace( $old_url = '', $new_url = '', $data = '', $serialised = false ) {
    $new_url = rtrim( $new_url, '/' );
    $data = explode( ', ', $data );
    try {
        if ( is_string( $data ) && ( $unserialized = @unserialize( $data ) ) !== false ) {
            $data = recursive_unserialize_replace( $old_url, $new_url, $unserialized, true );
        } elseif ( is_array( $data ) ) {
            $_tmp = array( );
            foreach ( $data as $key => $value ) {
                $_tmp[ $key ] = recursive_unserialize_replace( $old_url, $new_url, $value );
            }
            $data = $_tmp;
            unset( $_tmp );
        } else {
            if ( is_string( $data ) ) {
                $data = str_replace( $old_url, $new_url, $data );
            }   
        }
        if ( $serialised ) {
            return serialize( $data );
        }
    } catch( Exception $error ) {
    }
    return $data;
}

有什么想法吗?

对于任何感兴趣的人,这就是我想出的解决方案:

function unserialize_replace( $old_url = '', $new_url = '', $database_string = '' ) {
    if ( substr( $old_url, -1 ) !== '/' ) {
        $new_url = rtrim( $new_url, '/' );
    }
    $serialized_arrays = preg_match_all( "/a:d+:.*;}+/", $database_string, $matches );
    if( !empty( $serialized_arrays ) && is_array( $matches ) ) {
        foreach ( $matches[ 0 ] as $match ) {
            $unserialized = @unserialize( $match );
            if ( $unserialized ) {
                $buffer = str_replace( $old_url, $new_url, $unserialized );
                $buffer = serialize( $buffer );
                $database_string = str_replace( $match, $buffer, $database_string );
            }
        }
    }
    if ( is_string( $database_string ) ) {
        $database_string = str_replace( $old_url, $new_url, $database_string );
    }
    return $database_string;
}

感谢您的建议。如果您发现任何错误以及我可以改进的任何事情,请告诉我

最新更新