Reputation: 3
My problem is how to get substring from character until character in php.
I have tried this :
<?php
$str = "I love my family";
echo substr($str, 'm', strpos($str, 'y'));
?>
It shows following error:
Message: substr() expects parameter 2 to be long, string given
expected result is : my family
Upvotes: 0
Views: 2422
Reputation: 2492
Something along these lines :
$str = "I love my family"; $from_char = 'm'; $to_char = 'y';
// Find position of the $from_char
$from_pos = strpos( $str, $from_char );
// Now find position of blank space after $from_pos
$blank_space_pos = strpos( $str, ' ', $from_pos );
// Find position of $to_char after $blank_space_pos
$to_pos = strpos( $str, $to_char, $blank_space_pos );
// Using $from_pos and $to_pos , get the substring
echo substr( $str, $from_pos, $to_pos-$from_pos+1 );
Or something along these :
$str = "I love my family"; $from_char = 'm'; $to_char = 'y';
$from_pos = strpos( $str, $from_char ); // strpos finds first occurrence
$to_pos = strrpos( $str, $to_char ); // strrpos finds last occurrence
echo substr( $str, $from_pos, ( $to_pos-$from_pos+1 ) );
Both output :
my family
Upvotes: 1
Reputation: 4689
Second parameter of substr() must not be string. It should be integer. See this. So you have to write something like
echo substr($str, strpos($str, 'm'), strpos($str, 'y') - strpos($str, 'm') + 1);
(because third parameter is length, not position)
But this is not solution too, because you have 'y' not only at the end of the string (first 'y' is in word 'my', so this code returns only 'my'). So it is better to have another creteria of output string (not from 'm' to 'y', but from 'm' to end of line, for example echo substr($str, strpos($str, 'm'));
)
Upvotes: -1
Reputation: 3862
used this code:
<?php
$str = "I love my family";
echo substr($str, strpos($str, 'm') , strpos($str, 'y')+1);
?>
Upvotes: 0
Reputation: 173562
To get everything from "m" onwards, you can use strstr()
:
echo strstr('i love my family', 'm'); // my family
The example you gave isn't very good, because the string between "m" and "y" (inclusive) is "my". That aside, you can use strpos()
to find the range:
$str = 'i love my family';
if (($start = strpos($str, 'm')) !== false && ($stop = strpos($str, 'y', $start)) !== false) {
echo substr($str, $start, $stop - $start + 1);
}
Upvotes: 1
Reputation: 56992
if you are not particular with using substr
strstr
can do the job.
$str = "I love my family";
echo strstr($str, 'm'); // my family
echo strstr($str, 'm', true); // I love
http://php.net/manual/en/function.strstr.php
Upvotes: 2
Reputation: 23958
Corrected code:
<?php
$str = "I love my family";
$pos = strpos($str, ' m');
echo substr($str, $pos);
?>
Upvotes: 0