Reputation: 630
I want to split words from string. for example, my string is "In the #name of god" and i need the "name" only!! but when i use this snipet, return me "name of god"
$string = "In the #name of god";
$word = explode( '#', $string );
echo $word;
Upvotes: 1
Views: 2393
Reputation: 47764
In my own project, I would certainly avoid making a handful of function calls to replicate what can be done with one preg_
function call.
Effectively, match the literal #
, then "forget" it with \K
, then match one or more non-whitespace characters. The fullstring match is accessed by index 0
if there is a match in the string.
Code: (Demo)
$string = "In the #name of god";
echo preg_match('~#\K\S+~', $string, $match) ? $match[0] : '';
// output: name
Upvotes: 0
Reputation: 2847
There are a couple options (also preg_match would help for multiple instances of '#')
<?php
//With Explode only (meh)
$sen = "In the #name of god";
$w = explode(' ', explode('#',$sen)[1])[0];
echo $w;
//With substr and strpos
$s = strpos($sen , '#')+1; // find where # is
$e = strpos(substr($sen, $s), ' ')+1; //find i
$w = substr($sen, $s, $e);
echo $w;
//with substr, strpos and explode
$w = explode(' ', substr($sen, strpos($sen , '#')+1))[0];
echo $w;
Upvotes: 0
Reputation: 718
$string = "In the #name of god";
// Using `explode`
$word = @reset(explode(' ', end(explode( '#', $string ))));
echo $word; // 'name'
// Using `substr`
$pos1 = strpos($string, '#');
$pos2 = strpos($string, ' ', $pos1) - $pos1;
echo substr($string, $pos1 + 1, $pos2); // 'name'
Note: The
@
character before thereset
function is an Error Control Operators. It avoid to display a warning message when usingend
function with a non-reference variable, and yes, it's a bad practice. You should create your own variable and pass toend
function. Like this:
// Using `explode`
$segments = explode( '#', $string );
$segments = explode(' ', end($segments));
$word = reset($segments);
echo $word; // 'name'
Upvotes: 5
Reputation: 528
Sorry, I just readed it wrong.
Explode converts an String into Array. So your output'll result in ["In the ", "name of god"]. If you want to catch an word on it you need to be more specific on how it'll work. If you just want to catch the first word after a hashtag you should use strpos and substr.
$string = "In the #name of god";
$hashtag_pos = strpos($string, "#");
if($hashtag_pos === false)
echo ""; // hashtag not found
else {
$last_whitespace_after_hashtag = strpos($string, " ", $hashtag_pos);
$len = $last_whitespace_after_hashtag === false ? strlen($string)-($hashtag_pos+1) : $last_whitespace_after_hashtag - ($hashtag_pos+1);
echo substr($string, $hashtag_pos+1, strpos($string, " ", $len));
}
Upvotes: 0
Reputation: 7896
try regex and preg_match
$string = "In the #name of god";
preg_match('/(?<=#)\w+/', $string, $matches);
print_r($matches);
Output:
Array ( [0] => name )
Upvotes: 1