PHP String Manipulation 1


PHP STRING MANIPULATION part 1

In PHP there are some functions that can be used to manipulate strings for example, to replace certain characters, remove spaces, and others. The following are the functions that are used in PHP to manipulate strings.

substr ()

The function substr () function is similar to array_slice () that takes a few characters that are determined by two parameters: the initial and final parameters. Writing: substr (string var, initial parameters, parameters end); Concerning the use of initial parameters and final parameters equal to array_slice () that is if the initial parameters do not have a negative sign, indicating the beginning of making the characters (with initial character record is zero) and if negative then the character-making starts from the last character of the value indicated by the initial parameters.

As for the parameters of the end, if there is no negative sign, then the value indicates the number of characters that were taken, whereas if there is a negative sign, then the decision-terminated character as much as initial parameter values ​​from the last character.

substr_replace ()
substr_replace () function to replace part or all of the characters is limited by the parameters start and end parameters.

The syntax is:

substr_replace($variable, $replacement, parameters_start, end);


For more details example:

<?
$string="abcdefghij";
$string1=substr($string,3);
$string2=substr($string,3,4);
$string3=substr($string,-4,3);
$string4=substr($string,-5,-2);
$pengganti="aku";
$string5=substr_replace($string,$replacement,3);
$string6=substr_replace($string,$replacement,3,4);
$string7=substr_replace($string,$replacement,-4,3);
$string8=substr_replace($string,$replacement,-5,-2);

echo("\$string = $string\n");
echo("<BR>substr(\$string,3) = $string1\n");
echo("<BR>substr(\$string,3,4) = $string2\n");
echo("<BR>substr(\$string,-4,3) = $string3\n");
echo("<BR>substr(\$string,-5,-2) = $string4\n");

echo("<P>\$replacement = $replacement \n");
echo("<BR>substr_replace(\$string,\$replacement,3) =
$string5\n");
echo("<BR>substr_replace(\$string,\$replacement,3,4)
= $string6\n");
echo("<BR>substr_replace(\$string,\$replacement,-4,3)
= $string7\n");
echo("<BR>substr_replace(\$string,\$replacement,-5,-
2) = $string8\n");
?>
trim ()
trim () function to remove spaces on the right and left of a string variable, for example:
<?
$char = " PHP Programming ";
echo (trim ($char));
?>
 
Output :

PHP Programming”
 
To eliminate the spaces to the left of the string use ltrim() function, while for the right use chop().

Continued in PHP String Manipulation Part 2

0 comments:

Post a Comment