On my site I want to detect if someone mentions a username in a comment, like so: what's up /u/username.
How exactly can I extract the characters following /u/ in a foreach loop?
Something like this:
if (strpos($commentString, '/u/') !== false) {
foreach /u/ in $commentString {
$username = the text immediately after /u/, stopping at anything that isn't a letter or a number
}
}
You can use preg_match_all with a regex of
/u/([a-z0-9]+)
to capture the usernames in the text. For example:
$text = "what's up /u/username have you seen /u/user21 today?";
preg_match_all('#/u/([a-z0-9]+)#i', $text, $matches);
foreach ($matches[1] as $user) {
echo "found user $user\n";
}
Output:
found user username
found user user21
Demo on 3v4l.org
Related
I receive a string like this:
class1 fa-dollar class2 class3
Now, i need to check this string for a string/word containing fa-*. How can I manage that with PHP?
Wordwise as code
if(custom_strpos($myReceivedString, 'fa-')) {
echo $faStringOnly;
// output: 'fa-dollar'
}
Thanks in advance.
Let's start with two code examples:
$example = "class1 fa-dollar class2 class3";
if (preg_match_all('/(fa-\w+)/', $example, $matches)) {
foreach ($matches[0] as $match) {
print $match . "\n";
}
}
$moreThan1 = "class1 fa-dollar class2 fa-other class3";
if (preg_match_all('/(fa-\w+)/', $example, $matches)) {
foreach ($matches[0] as $match) {
print $match . "\n";
}
}
First example is your example. We're using preg_match_all to match all instances. In your example, there is only one. The regular expression match is /fa-\w+/ which says "this match begins with fa- and then has 1 or more word-based characters. (I made this assumption based on fa-dollar which I'm assuming are classes from Font Awesome.
The found matches are put into $matches and the exmaple code shows how you can loop through them.
To show that this works with more than one match, you can see the second example.
I have this function, which color every #username contained in a string
//color #username
function hashtag_links($string,$id_session) {
preg_match_all('/#(\w+)/',$string,$matches);
foreach ($matches[1] as $match) {
$string = str_replace("#$match", "<span class=color>#$match</span>", "$string");
}
return $string;
}
Everything is good while the usernames are different (#cat,#pencil,#scubadiving), but in case the username starts with the same letters (#cat,#caterpiller,#cattering), the functions only colors the repeated letters in this case (#cat), what to do?
Use preg_replace instead:
//color #username
function hashtag_links($string,$id_session) {
return preg_replace('/#(\w+)/', '<span class=color>#$1</span>', $string);
}
Hmmm... assuming you have a string like this:
$string='Hey there, folks! #bob, #kevin, #bobby, #keverino';
I would try something like:
preg_replace('/(#[A-Za-z0-9]+)/','<span style="color:pink;">\1</span>',$string);
Of course, I don't know what your usernames can contain, so you might have to adjust the regex.
yesterday i asked a question that how to select specific word from string which is having # sign with it.
someone told me this solution
$abc = "hello #john what are you doing";
$found = preg_match('/#([^-\s]*)/', $abc, $matches);
$name = null;
if ($found) {
$name = $matches[1];
}
it works like a charm but the problem is it only select first word with # sign if the string have alot of words like that. so now i need a loop which selects all the words in string which are having # sign with them.
Use can use preg_match_all to get all matches of your regular expression, not just the first one.
$abc = "hello #john what on earth are #stella and #steve doing";
$found = preg_match_all('/#([^-\s]*)/', $abc, $matches);
if ($found) {
foreach ($matches[1] as $name) {
echo "Name: $name", PHP_EOL;
}
}
Output:
Name: john
Name: stella
Name: steve
I am trying to get all the sentence from text which contains set of sentences:
Here is my code and
http://ideone.com/fork/O9XtOY
<?php
$var = array('one','of','here','Another');
$str = 'Start of sentence one. This is a wordmatch one two three four! Another, sentence here.';
foreach ($var as $val)
{
$m =$val; // word
$regex = '/[A-Z][^\.\!\;]*('.$m.')[^\.;!]*/';
//
if (preg_match($regex, $str, $match))
{
echo $match[0];
echo "\n";
}
}
Why did it not print last sentence twice though I here and Another both appears in it
How can I skip sentence in the list if it already present? Want to remove the redundancy. I want to store sentence in some data structure/variable to use all such sentences later
I'd say your approach is a bit too convoluted. It's easier to:
first get all sentences,
and then filter this set by your criteria.
E.g:
// keywords to search for
$needles = array('one', 'of', 'here', 'Another');
// input text
$text = 'Start of sentence one. This is a wordmatch one two three four! Another, sentence here.';
// get all sentences (the pattern could be too simple though)
if (preg_match_all('/.+?[!.]\s*/', $text, $match)) {
// select only those fitting the criteria
$hits = array_filter($match[0], function ($sentence) use($needles) {
// check each keyword
foreach ($needles as $needle) {
// return early on first hit (or-condition)
if (false !== strpos($sentence, $needle)) {
return true;
}
}
return false;
});
// log output
print_r($hits);
}
demo: http://ideone.com/pZfOb5
Notes regarding:
if (preg_match_all('/.+?[!.]\s*/', $text, $match)) {
About the pattern:
.+? // select at least one char, ungreedy
[!.] // until one of the given sentence
// delimiters is found (could/should be extended as needed)
\s* // add all following whitespace
array_filter($match[0], function ($sentence) use($needles) {
array_filter just does what it's name suggests. It returns a filtered version of the input array (here $match[0]). The supplied callback (the inline function) get's called for each element of the array and should return true/false for whether the current element should be part of the new array.
The use-syntax allows access to the $needles-array, which is needed inside the function.
This will solve your problem
<?php
$var = array('one','of','here','Another');
$str = 'Start of sentence one. This is a wordmatch one two three four! Another, sentence here.';
foreach ($var as $val)
{
if (stripos($str,$val) !== false)
{
echo $val;
echo "\n";
}
}
i am using preg_replace for highlighting words in search results. search result sometimes also contains URL, not just text. and some URLs contain key words. then URLs get messed up as preg_replace also changes the URL.
is there any way to ignore URLs in preg_replace?
this is what i use:
$result = preg_replace('!('.$keyword.')!i', '<span style="background: #f00;">$1</span>', $result);
thank you!
Edited..
okay, than is this helpful?
Make your result as array and then check if it contains url?
<?php
$result = "This is Stpartāāa http://google.lv ";
$arr = explode(" ", $result);
foreach($arr as $key => $value) {
if ((strpos($value,'http://') !== false) AND (strpos($value,'www.') !== false)) {
// do nothing
} else {
// do somthing
}
}
?>