PHP查找字符串中的最长单词

要求简述:在一长串字符串中从左至右查找出最长的一个单词(忽略特殊符号),如果有多个单词同为最大长度,取最左边个。

原题:Using the PHP language, have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. 

Sample Test Cases:

Input:"fun&!! time"

Output:"time"


Input:"I love dogs"

Output:"love"


我的基本思路: ①、用正则匹配将字符串中的特殊字符(包括空格)转换为某一单一的特殊字符,这里我将所有特殊字符  转换为(|)。

    ②、再用正则将紧挨着的两个(|)合并成一个。

    ③、用explode()方法将字符串打散为一个数组。

    ④、用循环比较数组每个单元的长度,将遇到最大的长度脚标赋值给一全局变量。最后输出数组中的这个  值。

代码如下:

<?php
	function LongestWord($str) {  
		$str2='|';
		$pattern='/((?=[\x21-\x7e\s]+)[^A-Za-z0-9])/';
		$str3=preg_replace($pattern,$str2,$str);
		$pattern2='/[|]+/';
		$str4=preg_replace($pattern2,$str2,$str3);	
		$arr=explode('|', $str4);
		$a=0;
		$pos=0;
		foreach($arr as $key=>$v){
			$b=strlen($v);
			if($b>$a){
				$a=$b;
				$pos=$key;
			}
		}
		return $arr[$pos];
	}
	$str='fun&!! time';
	echo LongestWord($str); 

输出结果:

time

猜你喜欢

转载自blog.csdn.net/qq_23669731/article/details/78717070