簡體   English   中英

我應該如何重寫代碼?

[英]How should I rewrite the code?

<?php
$original_chars = array(
    '/A/','/B/','/C/'
);
$replaced_chars = array(
    'a','b','c'
);
$updated_filename = preg_replace( $original_chars, $replaced_chars, $filename );
?>

我需要將兩個帶有字符的數組合並為一個關聯數組。

我應該如何用之前的代碼示例中的preg_replace重寫行?

<?php
$array_chars = array(
    '/A/' => 'a',
    '/B/' => 'b',
    '/C/' => 'c'
);
//$updated_filename = preg_replace( $original_chars, $replaced_chars, $filename );
?>

您應該能夠使用array_keysarray_values (未經測試)

$updated_filename = preg_replace( array_keys($original_chars), array_values($replaced_chars), $filename );

首先,最好的方法是strtr()

$filename = strtr($filename, "ABC", "abc");

要么

$array_chars('A' => 'a', 'B' => 'b', 'C' => 'c');
$filename = strtr($filename, $array_chars);

為了將preg_replace與關聯數組一起use array_keys() ,必須use array_keys()

$result = preg_replace(array_keys($array_chars), $array_chars, $filename);

(請注意,這種方法不是很有用,並且不需要array_values() 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM