Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equivalent of JavaScript's substring()

Tags:

php

JavaScript has two handy substring functions: substring(from,to) and substr(start,length).

This means I can decide "when I get my substring starting from position X, do I want to specify what string position to end on or how many characters long the substring is?"

(One nice usage of the from, to version is to use search() to determine both positions.)

PHP's substr() lets you specify the length of the substring. Is there a built-in string function to let you specify the character position to end on?

like image 249
Nathan Long Avatar asked Dec 01 '22 05:12

Nathan Long


2 Answers

I think this question is more about logic. You can accomplish both with the substr() function.

For instance. for the First substring(from, to):

$string = 'Foo Bar!';
$from   = 2;
$to     = 5;
$final_string = substr($string, $from, $to - $from);

And the second substr(start,length):

$string = 'Foo Bar!';
$start  = 2;
$length = 5;
$final_string = substr($string, $start, $length);
like image 82
Nick Shepherd Avatar answered Dec 14 '22 22:12

Nick Shepherd


As an addition to Nick's answer, you can always write the substring function yourself:

function substring($string, $from, $to){
    return substr($string, $from, $to - $from);
}

I also have a PHP file with some JavaScript like function as the strtruncate() function and include them to the PHP script I need them for.

like image 37
2ndkauboy Avatar answered Dec 15 '22 00:12

2ndkauboy