首页 > 解决方案 > 从字符串中提取大写单词

问题描述

编辑我解决了我的问题。这是解决方案

$string = "Hello my Name is Paloppa. Im' 20 And? Hello! Words I  Io Man";     
// Word boundary before the first uppercase letter, followed by any alphanumeric character
preg_match_all( '/(?<!^)\b[A-Z][a-z]{1,}\b(?!["!?.\\\'])/', $string, $matches);
print_r( $matches[0] );

现在我还有一个问题

每次找到一个单词时,该单词就被插入到数组的某个位置。

如果我有这句话“你的名字和姓氏是什么?我的名字和姓氏是 Paolo Celio 和 Serie A Iim 25Thanksbro Bro Ciao”​​这是我的代码

    $string = "Whats is your Name and Surname? My Name And Surname' is Paolo Celio and Serie A Iim 25 Thanksbro Bro Ciao";     
// Word boundary before the first uppercase letter, followed by any alphanumeric character
preg_match_all( '/(?<!^)\b([A-Z][a-z]+ +){1,}\b(?!["!?.\\\'])/', $string, $matches);
print_r( $matches[0] );

输出如下

Array ( 
        [0] => Name 
        [1] => Name And Surname 
        [2] => Paolo Celio 
        [3] => Serie 
        [4] => Iim 
        [5] => Thanksbro Bro 
       )

为什么它不加入意甲而不是印A?为什么最后一个词不在输出中?

谢谢

编辑我解决了我的问题,这是我的正则表达式

preg_match_all('/(?<!^)\b[A-Z]([a-z0-9A-Z]| [A-Z]){1,}\b(?!["!?.\\\'])/', $string, $matches);

标签: phpregex

解决方案


您可以使用..

<?php
      $test="the Quick brown Fox jumps Over the Lazy Dog";
      preg_match_all("/[A-Z][a-z]*/",$test,$op);
      $output = implode(' ',$op[0]);
      echo $output;
?>

推荐阅读