[英]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 );
?>
I need to combine two arrays with chars into one associative array. 我需要将两个带有字符的数组合并为一个关联数组。
How should I rewrite the line with preg_replace from previous code sample? 我应该如何用之前的代码示例中的preg_replace重写行?
<?php
$array_chars = array(
'/A/' => 'a',
'/B/' => 'b',
'/C/' => 'c'
);
//$updated_filename = preg_replace( $original_chars, $replaced_chars, $filename );
?>
您应该能够使用array_keys
和array_values
(未经测试)
$updated_filename = preg_replace( array_keys($original_chars), array_values($replaced_chars), $filename );
First at all the best way to do that is strtr()
首先,最好的方法是strtr()
$filename = strtr($filename, "ABC", "abc");
or 要么
$array_chars('A' => 'a', 'B' => 'b', 'C' => 'c');
$filename = strtr($filename, $array_chars);
For the use of preg_replace with an associative array, you must use array_keys()
: 为了将preg_replace与关联数组一起use array_keys()
,必须use array_keys()
:
$result = preg_replace(array_keys($array_chars), $array_chars, $filename);
(note that this way is not very usefull and that array_values()
is not needed.) (请注意,这种方法不是很有用,并且不需要array_values()
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.