如何在PHP中查找没有空格和函数的字符串长度

时间:2016-02-26 13:50:41

标签: php

我有分配找到没有空格的字符串长度而没有使用任何字符串函数,任何人都可以帮助我

3 个答案:

答案 0 :(得分:2)

您可以使用正则表达式和函数preg_match_all

$value = "This is a test string.";
$length = preg_match_all ('/[^ ]/' , $value, $matches);
echo $length; //18

您可以在这里找到一个有效的例子:https://3v4l.org/IPlJi

<强>解释
[^]之间,您必须添加所有不应计入字符串长度的字符。例如:如果要过滤掉字符i(空格),则必须设置以下模式:[^ i]

过滤i(空格)的代码:

$value = "This is a test string.";
$length = preg_match_all('/[^ i]/' , $value, $matches);
echo $length; //15

小心一些字符:
如果您要排除以下字符之一.^$*+?()[{\|,则必须使用\转义它们。如果您也要排除.,则可以使用以下代码:

$value = "This is a test string.";
$length = preg_match_all ('/[^ \.]/' , $value, $matches);
echo $length; //18

如何测试您的模式:
如果您要测试preg_match_all或其他类似函数的正则表达式,可以使用以下工具:http://www.phpliveregex.com/

答案 1 :(得分:1)

这对你有用:

$string = "this is a nice string with spaces and chars";
$length = 0;
$i = 0;
while(isset($string[$i]))
{
  if($string[$i] != ' ') $length++;
  $i++;
}
var_dump($length);
var_dump(strlen($string));

输出:

int(35) 
int(43)

答案 2 :(得分:0)

  

它会帮助你Tahir Hassan先生离开这个engrezi gandu

<!doctype html>
<html>
  <body>
    <center>
      <form action="#" method="get">
        <br>
        <input type="text" name="txt"/>
        <br><br>
        <input type="submit" name="submit"/>
        <br><br>
      </form>
      <!---------------------------------------------------------------------->  
<?php
if(isset($_GET["submit"])) {
    $name = $_GET["txt"];
    for ($i = 0; isset($name[$i]); $i++) {
        $j = $i;
    }
    for ($k = $j; isset($name[$k]); $k--) {
        echo $name[$k];
    }
}