Slicing Strings

You can extract a portion of a string by using the substr() function.


Specify the start index and the number of characters you want to return.


Syntax:


substr(string $string, int $start, int $length = ?);


$string: The input string.

$start: The starting position to slice. A positive number counts from the beginning (0-indexed). A negative number counts from the end of the string.

$length (optional): The length of the substring to extract. If not provided, it extracts from $start to the end of the string. A negative value of $length will exclude characters from the end.

Example
<!DOCTYPE html>
<html>
<body>

<?php

$substring = substr("Hello World", 0, 5); // Outputs: Hello
echo $substring;

?>
</body>
</html>

Try it yourself

Note

The first character has index 0.

Slice to the End


By leaving out the length parameter, the range will go to the end:

Example
<!DOCTYPE html>
<html>
<body>

<?php

$text = "Hello, World!";

// Slice from index 7 to the end
$subText = substr($text, 7);
echo $subText; // Outputs: World!

?>


</body>
</html>

Try it yourself

Slice From the End


Use negative indexes to start the slice from the end of the string:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = "Hello World!";
echo substr($x, -5, 3);
?>

</body>
</html>

Try it yourself

Note

The last character has index -1.

Negative Length


When you pass a negative length value, it will exclude that many characters from the end of the string:


Example
<!DOCTYPE html>
<html>
<body>

<?php
$text = "Hello, World!";

// Start at position 0, and extract everything except the last 6 characters
$subText = substr($text, 0, -6);
echo $subText; // Outputs: Hello,
?>

</body>
</html>

Try it yourself

In this case:

  • 0 means start from the beginning of the string.
  • -6 means exclude the last 6 characters, so "Hello, " is returned.
Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.