select multi numbers of words after # sign from using php - php

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

Related

Get specific string from string, starting with pattern

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.

Find part of a string and output the whole string

I would like to find part of a string and if true I want to ouput the whole of the string that it finds.
Below is an example:
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
if(strstr($Find, $Towns)){
echo outputWholeString($Find, $Towns); // Result: Eccleston.
}
If anyone can shed some light on how to do this as well, and bare in mind that it will not be static values; the $Towns and $Find variables will be dynamically assigned on my live script.
Use explode() and strpos() as
$Towns = "Eccleston, Aberdeen, Glasgow";
$data=explode(",",$Towns);//
$Find = "Eccle";
foreach ($data as $town)
if (strpos($town, $Find) !== false) {
echo $town;
}
DEMO
You have to use strpos() to search for a string inside another one:
if( strpos($Towns, $Find) === false ) {
echo $Towns;
}
Note that you have to use "===" to know if strpos() returned false or 0.
The solution using preg_match function:
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
preg_match("/\b\w*?$Find\w*?\b/", $Towns, $match);
$result = (!empty($match))? $match[0] : "";
print_r($result); // "Eccleston"
Assuming that you will always have $Towns separated by ", " then you could do something like this
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
$TownsArray = explode(", ", $Towns);
foreach($TownsArray as $Town)
{
if(stristr($Find, $Town))
{
echo $Town; break;
}
}
The above code will output the Town once it finds the needle and exit the foreach loop. You could remove the "break;" to continue letting the script run to see if it finds more results.
Using preg_match(), it is possible to search for Eccle and return the Eccleston word.
I use the Pearl Compatible Regular Expression (PCRE) '#\w*' . $Find . '\w*#' in the code below and the demo code.
The # characters are PCRE delimiters. The pattern searched is inside these delimiters. Some people prefer / as delimiter.
The \w indicates word characters.
The * indicates 0 or more repetions of the previous character.
So, the #\w*Eccle\w*# PCRE searches for an string containing Eccle surrounded by one or more word characters (letters)
<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
if (preg_match('#\w*' . $Find . '\w*#', $Towns, $matches)) {
print_r($matches[0]);
}
?>
Running code: http://sandbox.onlinephpfunctions.com/code/4e4026cbbd93deaf8fef0365a7bc6cf6eacc2014
Note: '#\w*' . $Find . '\w*#' is the same as "#\w*$Find\w*#" (note the surrounding single or double quotes). See this.
You were nearly there...
This is probably what you are looking for:
<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
if(stripos($Towns, $Find)) {
echo $Towns;
}
The output is: Eccleston, Aberdeen, Glasgow which is what I would call "the whole string".
If however you only want to output that partly matched part of "the whole string", then take a look at that example:
<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
foreach (explode(',', $Towns) as $Town) {
if(stripos($Town, $Find)) {
echo trim($Town);
}
}
The output of that obviously is: Eccleston...
Two general remarks:
the strpos() / stripos() functions are better suited here, since they return only a position instead of the whole matched string which is enough for the given purpose.
the usage of stripos() instead of strpos() performs a case insensitive search, which probably makes sense for the task...

PHP check if two keywords occur in String

my challange explained on the following example: The keyword combination "gaming notebook" is given.
I want to check whether the two keywords occur in a string. The challange is that the string could look like this:
"Nice Gaming Notebook"
"Notebook for Gaming"
"Notebook for extreme Gaming"
I want my function to return true for all of the three strings. There is a tolerance of 3-4 words that can be between the word combination and as the examples show, I want it to work if the keywords are switched.
So my approach was the following, but it does not seem to work:
$keyword = strtolower("gaming notebook");
$parts = explode(" ", $keyword);
$string = strtolower("Which notebook for good gaming performance");
//point to end of the array
end($parts);
//fetch key of the last element of the array.
$lastElementKey = key($parts);
//iterate the array
$searchExpression = "";
foreach($parts as $k => $v) {
if($k != $lastElementKey) {
$searchExpression .= $v . "|";
} else {
$searchExpression .= $v;
}
}
if(preg_match_all('#\b('. $searchExpression .')\b#', $string, $matches) > 0) {
echo "Jep, keyword combination is in string";
} else {
echo "No, keyword combination is not in string";
}
You want to use something like CMU Sphinx or a natural language index in your database. (See http://dev.mysql.com/doc/refman/5.7/en/fulltext-natural-language.html) Doing a quick search of php libraries turned up "nlp-tools/nlp-tools," however, I have never used a pure php solution to accomplish what you are trying to do.
The solution using preg_match_all and array_intersect functions:
$keywordStr = "gaming notebook";
$string = "Which notebook for good gaming performance,it's my notebook";
$keywords = explode(" ", $keywordStr);
$parts = implode("|", $keywords);
preg_match_all("/\b$parts\b/i", $string, $matches);
// matched items should contain all needed keywords
if (count($keywords) == count(array_intersect($keywords, $matches[0]))) {
echo "Jep, keyword combination is in string";
} else {
echo "No, keyword combination is not in string";
}
<?php
$keyword = strtolower("gaming notebook");
$string = strtolower("Which notebooks for good gaming performance");
function check($keyword,$string){
$parts = explode(' ',$keyword);
$result = false;
$pattern = implode('|',$parts);
preg_match_all("(\b{$pattern}\b)",$string,$matches);
if(isset($matches[0])){
return true;
}
return false;
}
var_dump(check($keyword, $string));
$reg = "/(?:\b$kw1(?:\s+\w+){0,4}\s+$kw2\b)|(?:\b$kw2(?:\s+\w+){0,4}\s+$kw1\b)/";
if (preg_match($reg, $string)) {
echo "OK\n";
} else {
echo "KO\n";
}
This will echo OK when the 2 keywords occur in the string, in any order and separated by at most 4 words.
Explanation:
/
(?: : non capture group
\b$kw1 : keyword 1
(?:\s+\w+){0,4} : followed by 0 to 4 other word
\s+ : space(s)
$kw2\b : keyword 2
)
|
(?: : non capture group
\b$kw2 : keyword 2
(?:\s+\w+){0,4} : followed by 0 to 4 other word
\s+ : space(s)
$kw1\b : keyword 1
)
/

Preg Replace with mentions

I have some problems with the preg_replace.
I would change the mentions in a links but the name isn't a username.
So in the name there are spaces, i found a good solution but i don't know to do it.
Sostantially i would that preg_replace the words that are between # and ,
For example:
#John Doeh, #Jenna Diamond, #Sir Duck Norman
and replace to
VAL
How do I do it?
I think that you want it like:
John Doeh
For this try:
$myString="#John Doeh, #Jenna Diamond, #Sir Duck Norman";
foreach(explode(',',$myString) as $str)
{
if (preg_match("/\\s/", $str)) {
$val=str_replace("#","",trim($str));
echo "<a href='user.php?name=".$val."'>".$val."</a>";
// there are spaces
}
}
Based on my assumption you want to remove strings which start with #Some Name, in a text like: #Some Name, this is a message.
Then replace that to an href, like: First_Name
If that is the case then the following regex will do:
$str = '#First_Name, say something';
echo preg_replace ( '/#([[:alnum:]\-_ ]+),.*/', '$1', $str );
Will output:
First_Name
I also added support for numbers, underscores and dashes. Are those valid in a name aswell? Any other characters that are valid in a #User Name? Those are things that are important to know.
Two methods:
<?php
// preg_replace method
$string = '#John Doeh, #Jenna Diamond, #Sir Duck Norman';
$result = preg_replace('/#([\w\s]+),?/', '$1', $string);
echo $result . "<br>\n";
// explode method
$arr = explode(',', $string);
$result2 = '';
foreach($arr as $name){
$name = trim($name, '# ');
$result2 .= ''.$name.' ';
}
echo $result2;
?>

Preg match question

I'm sure someone already asked this question, but after searching for more than 1 hour on google, I decided to ask my question here.
I want to itterate over an array excisting of different strings/texts.
These texts contain strings with both ##valuetoreplace## and #valuetoreplace#
I want to make to preg_matches:
$pattern = '/^#{1}+(\w+)+#{1}$/';
if(preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE))
{
// do something with the #values#
}
AND
$pattern = '/^#{2}+(\w+)+#{2}$/';
if(preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE))
{
//do something with the ##value##
}
This works great.
Now my only problem is as follows:
When i have a string like
$valueToMatch = 'proceding text #value#';
My preg_match cant find my value anymore (as i used a ^ and a $).
Question: how can i find the #value# and the ##value##, without having to worry if these words are in the middle of a (multi-line) value?
*In addition:
What i want is to find patterns and replace the #value# with a db value and a ##value## with a array value.
For example:
$thingsToReplace = 'Hello #firstname# #lastname#,
How nice you joined ##namewebsite##.';
should be
'Hello John Doe,
How nice you joined example.com.'
Try this: /##([^#]+)##/ and /#([^#]+)#/, in that order.
Maybe nice to know for other visitors how i did it:
foreach($personalizeThis as $key => $value)
{
//Replace ##values##
$patternIniData = '/#{2}+(\w+)#{2}/';
$return = 'website'; //testdata
$replacedIniData[$key] = preg_replace($patternIniData, $return, $value);
//Replace #values#
$pattern = '/#{1}+(\w+)#{1}/';
$return = 'ASD'; //testdata
$replacedDbData[$key] = preg_replace($pattern, $return, $replacedIniData[$key]);
}
return $replacedDbData;

Categories