PHP正则表达式 - 从字符串中的最后一个单词中删除所有字符

时间:2022-10-16 12:15:05

I researched quite a long time before posting, but I couldn't come up with an answer.

我在发帖前研究了很长时间,但我无法想出答案。

I'm trying to remove all characters but the first from a string. The string is going to be a name. The name can have a first name and a last name, as well as a middle name. So my task is to explode the string into words and find the last one, remove the characters and add a dot to the first letter. Moreover, if present in the string, the middle name should not be in the result.

我试图删除所有字符,但第一个字符串。该字符串将成为一个名称。名称可以具有名字和姓氏,以及中间名称。所以我的任务是将字符串分解为单词并找到最后一个,删除字符并在第一个字母上添加一个点。此外,如果字符串中存在,则中间名称不应出现在结果中。

For example: Chuck Ray Norris should transform into Chuck N.

例如:Chuck Ray Norris应该转变为Chuck N.

I tried a couple of regex and strpos but this task is too difficult for me and my skills.

我尝试了几个正则表达式和strpos,但这个任务对我和我的技能来说太难了。

5 个解决方案

#1


A non-regex solution for "FirstName SecondName ThirdName... LastName" pattern:

“FirstName SecondName ThirdName ... LastName”模式的非正则表达式解决方案:

<?php
$str = "Chuck Ray Norris";
$spls = explode(" ", $str);
echo $spls[0] . " " . $spls[count($spls)-1][0] . ".";

Output:

Chuck N.

#2


You can use:

您可以使用:

$s = 'Chuck Ray Norris';
$r = preg_replace('/^(\S+)\s+(?:\S+\s+)*(\S)\S*$/', '$1 $2.', $s);
//=> Chuck N.

$s = 'Chuck Norris';
$r = preg_replace('/^(\S+)\s+(?:\S+\s+)*(\S)\S*$/', '$1 $2.', $s);
//=> Chuck N.

$s = 'Chuck N.';
$r = preg_replace('/^(\S+)\s+(?:\S+\s+)*(\S)\S*$/', '$1 $2.', $s);
//=> Chuck N.

(?:\S+\s+)* is used for making 1 or more middle names optional. It also takes care of the case when name is already in desired format (case 3 above).

(?:\ S + \ s +)*用于使1个或多个中间名可选。当名称已经是所需的格式时,它还会处理这种情况(上面的案例3)。

#3


i don't know if this will work, but try this

我不知道这是否有效,但试试这个

<?php

$fullName = 'Chuck Ray Norris';
//$fullName = 'Chuck Ray';
//$fullName = 'Chuck';

$names = explode(' ', $fullName);
if((count($names) == 3) && isset($names[2])){
    echo $names[0] . ' ' . $names[2][0] . '.';
}else{
    if((count($names) == 2) && isset($names[1])){
        echo $names[0] . ' ' . $names[1][0] . '.';
    }else{
        echo $names[0];
    }
}

?>

try to change the $fullName to 'Chuck Ray' or 'Chuck' its still working also.

尝试将$ fullName更改为'Chuck Ray'或'Chuck',它仍然有效。

#4


This is how I would do it:

我就是这样做的:

$pos = strrpos($string, " ");

$pos = $pos === false ? 0 : $pos + 1;

$char = substr($string,$pos,1);

#5


Alternatively, if it is just a string with the requirements:

或者,如果它只是一个符合要求的字符串:

Chuck Ray Norris -> Chuck N

Chuck Ray Norris - > Chuck N.

Then using explode(), substr() and strlen():

然后使用explode(),substr()和strlen():

<?php
  $string = "Chuck Ray Norris";

  // break string into words
  $array = explode(" ", $string);

  // keep the first word, keep the last word's first character
  // ensure we have broken into vaid parts
  $length = count($array);
  if($length > 2) {
    // ie. Chuck Norris
    $first_word = $array[0];
    $last_word = $array[$length-1];

    // get first character, 
    $first_character = substr($last_word, 0, 1);
  }
  // else case is omitted

  print "$first_word $first_character\n"; // outputs Chuck N

?>

string substr ( string $string , int $start [, int $length ] )

string substr(string $ string,int $ start [,int $ length])

Ex: substr($last_word, 0, 1)

例如:substr($ last_word,0,1)

  • int $start: the length of "Norris" is 6, so first position is 0
  • int $ start:“Norris”的长度为6,因此第一个位置为0

  • int $length: we need only 1 character, therefore position 0, "N";
  • int $ length:我们只需要1个字符,因此位置0,“N”;

Hope this helps.

希望这可以帮助。

#1


A non-regex solution for "FirstName SecondName ThirdName... LastName" pattern:

“FirstName SecondName ThirdName ... LastName”模式的非正则表达式解决方案:

<?php
$str = "Chuck Ray Norris";
$spls = explode(" ", $str);
echo $spls[0] . " " . $spls[count($spls)-1][0] . ".";

Output:

Chuck N.

#2


You can use:

您可以使用:

$s = 'Chuck Ray Norris';
$r = preg_replace('/^(\S+)\s+(?:\S+\s+)*(\S)\S*$/', '$1 $2.', $s);
//=> Chuck N.

$s = 'Chuck Norris';
$r = preg_replace('/^(\S+)\s+(?:\S+\s+)*(\S)\S*$/', '$1 $2.', $s);
//=> Chuck N.

$s = 'Chuck N.';
$r = preg_replace('/^(\S+)\s+(?:\S+\s+)*(\S)\S*$/', '$1 $2.', $s);
//=> Chuck N.

(?:\S+\s+)* is used for making 1 or more middle names optional. It also takes care of the case when name is already in desired format (case 3 above).

(?:\ S + \ s +)*用于使1个或多个中间名可选。当名称已经是所需的格式时,它还会处理这种情况(上面的案例3)。

#3


i don't know if this will work, but try this

我不知道这是否有效,但试试这个

<?php

$fullName = 'Chuck Ray Norris';
//$fullName = 'Chuck Ray';
//$fullName = 'Chuck';

$names = explode(' ', $fullName);
if((count($names) == 3) && isset($names[2])){
    echo $names[0] . ' ' . $names[2][0] . '.';
}else{
    if((count($names) == 2) && isset($names[1])){
        echo $names[0] . ' ' . $names[1][0] . '.';
    }else{
        echo $names[0];
    }
}

?>

try to change the $fullName to 'Chuck Ray' or 'Chuck' its still working also.

尝试将$ fullName更改为'Chuck Ray'或'Chuck',它仍然有效。

#4


This is how I would do it:

我就是这样做的:

$pos = strrpos($string, " ");

$pos = $pos === false ? 0 : $pos + 1;

$char = substr($string,$pos,1);

#5


Alternatively, if it is just a string with the requirements:

或者,如果它只是一个符合要求的字符串:

Chuck Ray Norris -> Chuck N

Chuck Ray Norris - > Chuck N.

Then using explode(), substr() and strlen():

然后使用explode(),substr()和strlen():

<?php
  $string = "Chuck Ray Norris";

  // break string into words
  $array = explode(" ", $string);

  // keep the first word, keep the last word's first character
  // ensure we have broken into vaid parts
  $length = count($array);
  if($length > 2) {
    // ie. Chuck Norris
    $first_word = $array[0];
    $last_word = $array[$length-1];

    // get first character, 
    $first_character = substr($last_word, 0, 1);
  }
  // else case is omitted

  print "$first_word $first_character\n"; // outputs Chuck N

?>

string substr ( string $string , int $start [, int $length ] )

string substr(string $ string,int $ start [,int $ length])

Ex: substr($last_word, 0, 1)

例如:substr($ last_word,0,1)

  • int $start: the length of "Norris" is 6, so first position is 0
  • int $ start:“Norris”的长度为6,因此第一个位置为0

  • int $length: we need only 1 character, therefore position 0, "N";
  • int $ length:我们只需要1个字符,因此位置0,“N”;

Hope this helps.

希望这可以帮助。