Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - PHP Built-in Functions for Strings

By: FYICenter.com

Part:   1  2  3  4   5 

(Continued from previous part...)

How To Convert Strings in Hex Format?

If you want convert a string into hex format, you can use the bin2hex() function. Here is a PHP script on how to use bin2hex():

<?php
$string = "Hello\tworld!\n";
print($string."\n");
print(bin2hex($string)."\n");
?>

This script will print:

Hello   world!

48656c6c6f09776f726c64210a

How To Generate a Character from an ASCII Value?

If you want to generate characters from ASCII values, you can use the chr() function. chr() takes the ASCII value in decimal format and returns the character represented by the ASCII value. chr() complements ord(). Here is a PHP script on how to use chr():

<?php 
print(chr(72).chr(101).chr(108).chr(108).chr(111)."\n");
print(ord("H")."\n");
?>

This script will print:

Hello
72

How To Convert a Character to an ASCII Value?

If you want to convert characters to ASCII values, you can use the ord() function, which takes the first charcter of the specified string, and returns its ASCII value in decimal format. ord() complements chr(). Here is a PHP script on how to use ord():

<?php 
print(ord("Hello")."\n");
print(chr(72)."\n");
?>

This script will print:

72
H

How To Split a String into Pieces?

There are two functions you can use to split a string into pieces:

  • explode(substring, string) - Splitting a string based on a substring. Faster than split().
  • split(pattern, string) - Splitting a string based on a regular expression pattern. Better than explode() in handling complex cases.

Both functions will use the given criteria, substring or pattern, to find the splitting points in the string, break the string into pieces at the splitting points, and return the pieces in an array. Here is a PHP script on how to use explode() and split():

<?php 
$list = explode("_","php_strting_function.html");
print("explode() returns:\n");
print_r($list);
$list = split("[_.]","php_strting_function.html");
print("split() returns:\n");
print_r($list);
?>

This script will print:

explode() returns:
Array
(
    [0] => php
    [1] => strting
    [2] => function.html
)
split() returns:
Array
(
    [0] => php
    [1] => strting
    [2] => function
    [3] => html
)

The output shows you the power of power of split() with a regular expression pattern as the splitting criteria. Pattern "[_.]" tells split() to split whenever there is a "_" or ".".

(Continued on next part...)

Part:   1  2  3  4   5 


Selected Developer Jobs:

More...