我有一个包含这样的值的数组变量:
$items = array(
"tbFrench",
"eaItaly1",
"discount21",
"kkMM5",
"NbndA",
"fcMNSS334"
);
如果最后一个字符包含数字,则需要从此数组值中删除字符串的最后一个字符,例如:
$newItems = array();
foreach($items as $item){
$newItems[] = $this->removeLastCharacter($item);
}
print_r($newItems);
....
function removeLastCharacter($string){
// ????
}
当我print_r
$newItems
变量时,我希望结果看起来像这样:
Array ( [0] => tbFrench [1] => eaItaly [2] => discount2 [3] => kkMM [4] => NbndA [5] => fcMNSS33 )
答案 0 :(得分:2)
您可以使用正则表达式删除最后一位。
function removeLastCharacter($string){
return preg_replace('[\d$]', '', $string);
}
\d
匹配每个数字,$
引用字符串的结尾。因此,只有在末尾是数字时,才会替换最后一个字符。
答案 1 :(得分:1)
您只需将数组作为主题即可对数组中的所有项目进行RegEx替换,如下所示:
$items = preg_replace('/^d$/', '', $items);
根本不需要将其放入函数中-print_r($items)
输出:
Array
(
[0] => tbFrench
[1] => eaItaly
[2] => discount2
[3] => kkMM
[4] => NbndA
[5] => fcMNSS33
)
如果您要替换所有后缀数字,可以使用/^\d+$/
答案 2 :(得分:0)
如果可以解决您的问题,请尝试以下代码
$items = array(
"tbFrench",
"eaItaly1",
"discount21",
"kkMM5",
"NbndA",
"fcMNSS334"
);
$newArr=array();
foreach($items as $item){
$data = preg_replace('[\d$]','',$item);
array_push($newArr,$data);
}
print_r($newArr);
答案 3 :(得分:0)
为什么不简单?
print_r( preg_replace( '/\d+$/', "", $items ) ); // preg_replace accepts an array as argument, pass yours directly, no need for a loop.
Array
(
[0] => tbFrench
[1] => eaItaly
[2] => discount
[3] => kkMM
[4] => NbndA
[5] => fcMNSS
)
正则表达式说明:
\d+ — matches a digit (equal to [0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
$ — asserts position at the end of a line
答案 4 :(得分:0)
使用rtrim有一个快速窍门。
<?php
$conn = mysqli_connect("localhost", "root", "", "channels");
if(isset($_POST['channel_name']) && $_POST['channel_name'] != "") {
$dir = UUID();
// I think channelname is an error as well.
$channelname = $_POST['channel_name'];
mkdir($dir, 0777, true);
// I know there may be a syntax error in $index
$index = fopen($dir. "/index.php", "w");
fclose($index);
copy("index.php",$index);
// Insert values into table
$q = "INSERT INTO channels (dir, name) VALUES ($dir, $channelname)";
$query = mysqli_query($conn, $q);
if($query == true) {
echo "your channel has been created";
} else {
echo "there was an error";
};
};
?>
第二个参数是使用2个点“ ..”的范围。
您完成了!!!