Skip to content

PHP remove all characters before specific string

You can use the strstr() function in PHP to remove all characters before a specific string. The strstr() function returns the portion of the haystack string from the first occurrence of the needle to the end of the haystack string.

For example, to remove all characters before the string "example" in the string $haystack:

Example of removing all characters before a specific string in PHP

php
<?php

$haystack = "This is an example string.";
$needle = "example";
$newString = strstr($haystack, $needle);
echo $newString;

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

Alternatively you can use strpos() and substr() function to remove all characters before a specific string

Example of using strpos() and substr() function to remove all characters before a specific string in PHP

php
<?php

$haystack = "This is an example string.";
$needle = "example";
$pos = strpos($haystack, $needle);
$newString = substr($haystack, $pos);
echo $newString;

Both examples will return a new string containing only the characters after the first occurrence of the needle.

Dual-run preview — compare with live Symfony routes.