Search notes:

PHP code snippets related to strings

Some PHP functions that are related to strings include:
strcmp(), strcasecmp() Compare two strings. strcasecmp() compares the case insensitively.
preg_match()
substr_compare()
strncasecmp()
strstr(), stristr()
strpos()
strpbrk()
substr()
explode() Returns an array of strings that are created from a string by splitting this string on a delimiter.

String concatenation

Strings can be concatenated with the dot. There are two versions: $str_1 . $str_2 and $str_1 .= $str_2.
<html>
<head><title>String concatenation</title></head>
<body>

<?php
  $six     = "six ";
  $seven   = "seven ";

  $text    = "one ";
  $text    = $text . "two ";
  $text   .= "three ";
  $text   .= "four " . "five " . $six . $seven;

  print "text: " . $text;

?>

</body>
</html>
Github repository about-php, path: /string/concatenation.html

substr

substr() (substring) returns a portion of a string:
<html><head><title>Add elements to an array</title></head>
<body>

  <?php 
   
 //
 // Create an array with three elements:
 //
    $a = array('one', 'two', 'three');
    
 //
 // Append 'four' to the array:
 //
    $a[] = 'four';                     // Append 'four' to the array:

 //
 // same thing, but with array_push
 //
    array_push($a, 'five');

 //
 // Print elements
 //
    foreach ($a as $val) {
       print("<br>$val");
    }

  ?>

</body>
</html>
Github repository about-php, path: /array/add-elements.html

str_replace

str_replaces replaces a portion of a string with another (sub-)string.
<html>
<head><title>str_replace</title></head>
<body>

<?php

  $str  = "foo orange baz orange end";

  $repl = str_replace('orange', 'bar', $str);

  print "<b>str</b>: $str<br><b>repl</b>: $repl";

?>

  <p>See also <a href='preg_replace.html'>preg_replace.html</a>

</body>
</html>

Github repository about-php, path: /string/str_replace.html
Compare with PHP's regular expressions

explode

explode($delim, $txt) returns an array of strings whose elements are the substrings in $txt that are delimited by $delim.
explode() has an optional third argument that controls the maximum number of elements in the returned array.
<?php

header('Content-Type: text/plain');

printQueryOfURI('https://foo.bar/baz');
printQueryOfURI('https://foo.bar/baz?val=one');
printQueryOfURI('https://foo.bar/baz?v1=one&v2=two');
printQueryOfURI('https://foo.bar/baz?this=wrong?query');

function printQueryOfURI($uri) {

  $res = explode('?', $uri, 2); // 2: limit result to maximally two elements

  $url   = $res[0];
  if (count($res) == 2) {
     $query = $res[1];
  }
  else {
     $query = '';

  }

  printf("%-22s %s\n", $url, $query);

}

?>
Github repository about-php, path: /string/explode.php
Together with list(), the returned array can be assigned to named variables in one go (similar to assign the return value to a tuple in Python):
list($x, $y, $z) = explode('/', $xyz);

See also

Other PHP snippets

Index