Web Development & WordPress

Understanding PHP Spaceship Operator for Comparing Values

The spaceship operator (<=>) in PHP is used for comparing two values and returns -1, 0, or 1 depending on whether the first value is less than, equal to, or greater than the second value. Introduced in PHP 7, it simplifies comparisons and is especially useful for sorting functions.

CODE:

Continue reading “Understanding PHP Spaceship Operator for Comparing Values”
Web Development & WordPress

Mastering PHP String Search: The Differences Between strpos, stripos, and strripos Explained

  • stripos searches for the first occurrence of a substring in a string, ignoring case.
  • strripos searches for the last occurrence of a substring in a string, ignoring case.

CODE:

<?php
$string = "This is a test by Tom. He is a good boy. This is another test";
echo "Main sentence is:<br>";
echo $string;
echo '<br>Search the word "test" using strpos() <br>';
echo strpos($string, "test");

echo '<br>Search the word "Test" using strpos() <br>';
echo strpos($string, "Test");
if(strpos($string, "Test")){
    echo "Word Found";
}else{
    echo "Word not found--as strpos() is case sensitive";
}
echo '<br>Search the word "Test" using stripos()-- case sensitive <br>';
echo stripos($string, "Test");

echo '<br>Search the word "This" using stripos()-- case sensitive <br>';
 echo stripos($string, "This");
echo "<br>";
if(stripos($string, "This") !== false ){
    echo " Word  is found";
}else{
    echo "Word not found";
}
echo '<br>Search the word "This" using strripos()-- case sensitive. <br>';
 echo strripos($string, "This");

echo "<br>";
echo "Another Test<br>";

 $text = "This is a test. This is only a test.";
echo $text;
echo "<br>";
 $substring = "test";

$firstPos = stripos($text, $substring); 
$lastPos = strripos($text, $substring);  

echo "First occurrence of test: " . $firstPos . "\n";  
echo "Last occurrence of  test: " . $lastPos . "\n";    
?>
Continue reading “Mastering PHP String Search: The Differences Between strpos, stripos, and strripos Explained”
Web Development & WordPress

Split String or String tokenization

CODE:

<?php

$sentence ="Hello World, My name is Jimmy";
echo "split using explode<br>";
$split1= explode(" ",$sentence);
print_r($split1);
echo "<br>Join Splitted Sentence<br>";
$join1=join(" ",$split1);
echo $join1;
echo "<br>Join splitted sentence using implode<br>";
$join2 = implode(" ",$split1);
echo $join2;
echo "<br>Split string using multiple delimeter<br>";
$split2 = strtok($sentence," ,");

while ($split2 !== false){
    echo $split2."<br>";
    $split2=strtok(" ,");
}
print_r($split2);

echo "<br>Split string using regular expression <br>";

$split3= preg_split("/ |,/",$sentence);
print_r($split3);

echo "<br>Split \"Hello World\" in characters<br>";
echo <<<MyText
Split "Hello WOrld" in Characters <br>
MyText;
$split4 = str_split("Hello World");
print_r($split4);

?>
Continue reading “Split String or String tokenization”