首页 > 解决方案 > 用 php 解析一个短语(用空格分隔的单词)

问题描述

我正在尝试解析用空格分隔的短语并填写表格(请参见下图)。解析器必须检查每个单词是否

  1. 以 3 个字母字符结尾
  2. 以 3 个数字字符结尾
  3. 有特殊的性格

到目前为止,我能够使用下面的代码解析该短语,但是,我能够检查前三个字符,而不是最后三个字符。我也发现很难在表中包含对字符串中特殊字符的检查。有没有办法以更好的方式检查上述要求?先感谢您。

$words = 'The red fox eats meat, drinks and sleeps for 1000 hours';
$words=explode(' ', $input);//seperate the words and assign to an array
$wordCount=count($words);

<?php echo "<h1>Your Phrase has been Parsed</h1>"?>
<table>
    <thead>
       <td>Word</td>
       <td>Length</td>
       <td>Type</td>
    </thead>
        <tbody>
          <?php
           for($i=0; $i < $wordCount; $i++){
          ?>
                <tr>
                    <td><?php $wordTable = $words[$i]; echo $wordTable; ?></td>
                    <td><?php echo sprintf("%02d", strlen($wordTable))  ?></td>
                    <td>

                    <?php

                    $WT1=0;
                    $WT2=0;
                    $WT3=0;
 
                    if (strlen($wordTable) >= 3){
                        for($j=0; $j<3; $j++){

                            if(ctype_alpha($wordTable{$j})){
                                $WT1++;
                            }

                            else if(is_numeric($wordTable{$j})){
                                $WT2++;
                            }
                            else if(preg_match('[@_!#$%^&*()<>?/\|}{~:;,]',$wordTable{$j})){
                         
                                $WT3++;
                           }
                        }#for loop ends
                     }

                    ?>

                   <?php

                    if($WT1 == 3){
                        echo "word ends with 3 alphabetic characters";
                    }
                    else if($WT2 == 3){
                        echo "Ends with 3 digits";
                    }
                     else if ($WT3==TRUE){
                   echo "word has a special character";
                    }

                    else{
                        echo "Undefined type";
                    }

                    ?>

                    </td>

                </tr>
                <?php } ?>
            </tbody>

        </table>

标签: php

解决方案


我看到你已经使用了正则表达式。我建议将其扩展到整个脚本:

if (strlen($wordTable) >= 3) {
    if (preg_match('/[a-zA-Z]{3}$/', $wordTable)) {
        //case 1
    } elseif (preg_match('/[\d]{3}$/', $wordTable)) {
        //case 2
    } elseif (preg_match('/[\@\_\!\#\$\%\^\&\*\(\)\<\>\?\/\\\|\}\{\~\:\;\,]/', $wordTable)) {
        //case3
    } else {
        //undefined
    }
}

正则表达式的含义是:

  • [a-zA-Z]{3}$:在一组大小写字母中,必须有三个,位于单词的末尾 ($)。
  • [\d]{3}$:在一组数字中,必须有三个,位于单词的末尾 ($)。
  • 请注意,所有正则表达式都以分隔符开始和结束,我使用了斜杠。
  • 特殊字符必须用反斜杠转义。我不想检查你需要逃脱的那些,所以我把它们都逃脱了。

推荐阅读