How can I determine the length of a string in PHP without counting white spaces and without using built-in functions?

Solution: 1

You can count characters in a string (excluding certain characters) using regular expressions with preg_match_all().


$value = "This is a test string.";

// Count all characters except spaces
$length = preg_match_all('/[^ ]/', $value, $matches);
echo $length; // Output: 18

Excluding multiple characters

If you want to exclude specific characters (e.g., spaces and i):


$value = "This is a test string.";

// Exclude spaces and "i"
$length = preg_match_all('/[^ i]/', $value, $matches);
echo $length; // Output: 15

Escaping special characters

Some characters (.^$*+?()[{\|) must be escaped with a backslash. For example, to exclude spaces and the dot (.):


$value = "This is a test string.";

// Exclude spaces and "."
$length = preg_match_all('/[^ \.]/', $value, $matches);
echo $length; // Output: 18

Solution: 2

You can reverse a string using a simple loop in PHP, for example via an HTML form:


<!doctype html>
<html>
  <body>
    <center>
      <form action="#" method="get">
        <input type="text" name="txt" placeholder="Enter text"/>
        <br><br>
        <input type="submit" name="submit" value="Reverse"/>
        <br><br>
      </form>

      <?php
      if (isset($_GET["submit"])) {
          $name = $_GET["txt"];
          
          // Find the last index
          for ($i = 0; isset($name[$i]); $i++) {
              $j = $i;
          }

          // Print characters in reverse
          for ($k = $j; $k >= 0; $k--) {
              echo $name[$k];
          }
      }
      ?>
    </center>
  </body>
</html>

✅ How it works:

The first loop finds the last index of the string.

The second loop iterates backward from the last index, printing each character in reverse order.