user3452136
user3452136

Reputation: 125

How can I echo characters before and after a string?

I'm familiar with some of PHPs string functions, however I can't seem to find the right one to do what I want. What I'm trying to accomplish is to echo 22 characters before and after a string that I find. I'm able to find the starting position of the string as well as the string length...I'm thinking that these might be useful to accomplish what I need to. For example, let's say I find the string "hello". I want to echo "This is an example of hello how are you doing????" Will substr() accomplish this?

$var2 = 'hello';
$startingpos = strpos($var1, $var2));
$strlength = strlen($var2);

UPDATE: I've found the solution to my problem: Please see the below:

$additional_length = 2;
$startingpos = strpos($var1, $var2));
$strlength = strlen($var2);
if (($startingpos - $additional_length) < 0)
    $start = 0;
else
    $start = $startingpos - $additional_length;
echo substr($var2, $start, ($strlength + (2* $additional_length)))

Upvotes: 2

Views: 206

Answers (1)

WISERBIT
WISERBIT

Reputation: 111

You can easily set a constant inside your string, and then replace it with str_replace function.

For instance:

$results = str_replace("[FOUND]", "hello", "This is an example of [FOUND] how are you doing");

Working example:

function.onl/str_replace("[FOUND]", "hello", "This is an example of [FOUND] how are you doing");

Demo

Upvotes: 1

Related Questions