Reputation: 57
I asked a question yesterday that was superbly answered by several people (thank you).
New question :)
I want to extract a unique substring within a string, but also capture X number of characters before it. Is there any function that allows this?
I just found strrpos() -- this might do it.
Upvotes: 1
Views: 161
Reputation: 36351
you can also do this via regular expression:
<?php
function get($needle, $haystack, $before){
preg_match($v="/.{".$before."}$needle/", $haystack, $matches);
return $matches[0];
}
echo get("hello", "I just want to say hello bobby!", 3);
Upvotes: 1
Reputation: 33457
I don't think there's a built in to do this, but this should do the trick:
function subbef($str, $sub, $bef)
{
$pos = strpos($str, $sub);
if ($pos === false || $pos < $bef) {
return false;
}
return substr($str, $pos - $bef, strlen($sub) + $bef);
}
Usage is like:
subbef('test string here', 'string', 3); //"st string"
Upvotes: 1