Thursday, January 28, 2016

PHP: Fun with string functions

PHP


$var="Duis posuere nunc sit amet sapien pharetra, at scelerisque risus fringilla. Aenean sed purus nec quam ullamcorper aliquam.";

printf("%s %s","String equals:",$var);

echo "<pre>"; 

echo "<p><b>Substring: substr(\$var,12,9): ' nunc sit'</b></p>";

echo "<p>".substr($var,12,9)."</p>";

echo "<p><b>Substring and Subpoition: substr(\$var,27,6).' => '.strpos(\$var,'sapien'): sapien => 27</b></p>";

echo "<p>".substr($var,27,6)." => ".strpos($var,"sapien")."</p>";
echo "</pre>";

echo "<p><b>explode string and list</b></p>";

$arr=explode(" ",$var);

foreach($arr as $val){
  echo "<p>".$val."</p>";
}  


echo "<p><b>explode string to array and implode back to string (just because)</b></p>";
echo "<pre>";

echo "<p>".implode(" ",explode(" ",$var))."</p>";

echo "</pre>";
  

//Result


String equals: Duis posuere nunc sit amet sapien pharetra, at scelerisque risus fringilla. Aenean sed purus nec quam ullamcorper aliquam.
Substring: substr($var,12,9): ' nunc sit'
nunc sit
Substring and Subpoition: substr($var,27,6).' => '.strpos($var,'sapien'): sapien => 27
sapien => 27
explode string and list
Duis
posuere
nunc
sit
amet
sapien
pharetra,
at
scelerisque
risus
fringilla.
Aenean
sed
purus
nec
quam
ullamcorper
aliquam.
explode string to array and implode back to string (just because)
Duis posuere nunc sit amet sapien pharetra, at scelerisque risus fringilla. Aenean sed purus nec quam ullamcorper aliquam.

No comments:

Post a Comment