String Functions in PHP

The standard library in PHP provides many useful string-related functions. Here are some examples to give you a sense of these functions.

<?php

// We'll use a helper function to print our results
function p($label, $result) {
    echo $label . " " . var_export($result, true) . "\n";
}

// Here's a sample of the string functions available in PHP.
// These are built-in functions, so we don't need to import any packages.

p("Contains:  ", strpos("test", "es") !== false);
p("Count:     ", substr_count("test", "t"));
p("HasPrefix: ", str_starts_with("test", "te"));
p("HasSuffix: ", str_ends_with("test", "st"));
p("Index:     ", strpos("test", "e"));
p("Join:      ", implode("-", ["a", "b"]));
p("Repeat:    ", str_repeat("a", 5));
p("Replace:   ", str_replace("o", "0", "foo"));
p("Replace:   ", substr_replace("foo", "0", strpos("foo", "o"), 1));
p("Split:     ", explode("-", "a-b-c-d-e"));
p("ToLower:   ", strtolower("TEST"));
p("ToUpper:   ", strtoupper("test"));

To run this PHP script, save it to a file (e.g., string-functions.php) and execute it using the PHP command-line interpreter:

$ php string-functions.php
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       'a-b'
Repeat:     'aaaaa'
Replace:    'f00'
Replace:    'f0o'
Split:      array (
  0 => 'a',
  1 => 'b',
  2 => 'c',
  3 => 'd',
  4 => 'e',
)
ToLower:    'test'
ToUpper:    'TEST'

In this PHP version:

  1. We use built-in PHP functions for string operations instead of methods from a specific package.
  2. The strpos() function returns the index of the substring or false if not found, so we use !== false to check for containment.
  3. PHP doesn’t have a direct equivalent for strings.HasPrefix() and strings.HasSuffix(), so we use str_starts_with() and str_ends_with() which were introduced in PHP 8.0.
  4. For joining strings, we use implode() instead of a dedicated “join” function.
  5. The str_replace() function replaces all occurrences by default, so we don’t need to specify -1 as in Go.
  6. To replace only the first occurrence, we use substr_replace() with the position found by strpos().
  7. The explode() function is used for splitting strings in PHP.

These examples demonstrate how to perform common string operations in PHP, showcasing the language’s built-in string handling capabilities.