Pulling pieces of string

Very often there is a need to draw from the variable text only a portion thereof. The easiest way is if you know the length of the exhaust passage and a position in which it is located in a variable. Eg. If the variable contains „1999/10/20” We want to pull out the year.

It is known that a year is at the beginning and has 4 bytes. It is easiest to use the substr () project tracker. As the first parameter she gets the string from which will be extracted file as the second place, which will be started cutting (0 if the first character, a negative number if you want it to be the number of characters from the end), and the last, optional parameter indicates the number of characters to be cut (if you omit this parameter, it will be returned sub-sequence of the mark in the start to the end of the string).

Example
<?php

$data = „1999/10/20”

$year = substr ($ data, 0, 4);

?>

But, of course, the simplest of situations. A more complex example will draw from the same date in all the fields. Of course you can use 3 times the function substr, but more efficient method is to split the text on an array of arrays described by the way the function explode.
Example

<?php

$data = „1999/10/20”

$array = explode („/”, $ data);

?>

In the above example, the first element of the array will be located year in the second and third days from the date specified. You can also use this function in a more complex way – to break a string containing the date and time.
Example
<?php

$text = „19/11/1999 5:48:20″;

$dataiczas = explode (”, $ text);
$data = explode („/”, $datetime [0]);
$time = explode (‚:’, $datetime [1]);

?>

Now the array $ data contains the date, month and year and $array time hour, minute and second. But what if time includes hundredths of a second, which are served after the point? Do even one break? It is better to use funkcjisplit (), which funcjonuje in a similar way to explode, but the text does not breaks with the usual strings, but using regular expressions. Thus, the whole string containing the date and time can be broken down with a single function call split ().
Now in $ plaque will be placed one after the other day, month, year, hour, minute, second and hundredth of a second.
It may also be necessary to draw portions of a string to a character, eg. The first sentence of a text. Then you can use the call function substr () istrpos (), which returns the character number where the first occurrence of the string passed as the second parameter within specified as the first parameter, or false if the first string does not include the other.
Example
<?php

$text = „This is some text.”

$sentence = substr($text, 0, strpos ($text, „.”));

?>

Cookies help us deliver our services. By using our services, you agree to our use of cookies. More Info | Close