如何在php中提取字符串末尾的值


How to extract the value at the end of a string in php

在我的php代码中,我有一个变量数组,以一个单词开头,后跟一个(随机)数字:

x[0] = 'justaword8'
x[1] = 'justaword5'
x[2] = 'justaword4'
etc.

我知道我必须使用foreach循环,但如何提取每个单词末尾的数字?(我想我可以使用preg_match(),但不知道如何准确指定该函数?)

由于数字的长度在一位数或两位数之间变化,因此可以像这样使用preg_match()

foreach( $array as $x) {
    preg_match( '/('d{1,2})$/', $x, $match);
    echo "The number is: " . $match[1];
}

然而,由于前缀是提前知道的,只需直接删除它(根据Marc B的评论,带一个示例用法):

$prefix = "justaword";
$length = strlen( $prefix);
foreach( $array as $x) {
    echo "The number is: " . substr( $x, $length);
}

尝试使用这个:中工作评估(这将适用于一位数字)

foreach($x as $key => $value)
    echo substr($value,-1);

我已经针对两位数的情况进行了更新,没有regex的情况看起来有点粗糙,但如果出于某种原因您不想使用regex,则可以正常工作:(Working eval.in

<?php
$x[0] = 'justaword8';
$x[1] = 'justaword52';
$x[2] = 'justaword4';
foreach($x as $key => $value){
     $y = substr($value,'-2:');
     if(is_numeric($y)) // if last 2 chars are number
         echo $y; // return them
     else
         echo substr($y,1); // return only the last char
}
?>

如果"justaword"是常量,您可以使用str_replace('justaword','',$x[0]);来删除它。

您可以尝试此操作。它仅适用于一位

$str="justaword5";
echo $last_dig=substr($str,strlen($str)-1,strlen($str));

使用str_replace来修剪前缀。

$prefix = "justaword";
$words = array("justaword8", "justaword4", "justaword500");
$numbers = array();
foreach ($words as $word) {
    $numbers[] = str_replace($prefix, "", $word);
}
var_dump($numbers); // gives 8, 4, 500

代码:

 $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
 $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

输出:

 `Hll Wrld f PHP`

相反,您应该做的是让array是所有26个字符的数组。将所有字符替换为"后,您可以直接将字符串转换为数字!