Get specific string from string, starting with pattern - php

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.

Related

Get characters right after match in a foreach loop

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

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...

select multi numbers of words after # sign from using 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

Getting a word after a specific character in PHP

I want to get the words in a string where a specific character stands before, in this case, its the : character.
textexjkladjladf :theword texttextext :otherword :anotherword
From this snippet the expected output will be:
theword
otherword
anotherword
How do i do this with PHP?
You can use regular expression:
$string = "textexjkladjladf :theword texttextext :otherword :anotherword";
$matches = array();
preg_match_all('/(?<=:)\w+/', $string, $matches);
foreach ($matches[0] as $item) {
echo $item."<br />";
}
Output is:
theword
otherword
anotherword
The array what you want is the $matches[0]
Another way of getting those words without Regular Expression can be:
Use explode(' ',$str) to get all the words.
Then loop the words and check which one starts with ':'.
try
$str = 'textexjkladjladf :theword texttextext :otherword :anotherword';
$tab = exlode(':',$str);
print_r($tab);
//if echo entry 0 =>
echo $tab[0]; // => textexjkladjladf

regular expression word preceded by char

I want to grab a specific string only if a certain word is followed by a = sign.
Also, I want to get all the info after that = sign until a / is reached or the string ends.
Let's take into example:
somestring.bla/test=123/ohboy/item/item=capture
I want to get item=capture but not item alone.
I was thinking about using lookaheads but I'm not sure it this is the way to go. I appreciate any help as I'm trying to grasp more and more about regular expressions.
[^/=]*=[^/]*
will give you all the pairs that match your requirements.
So from your example it should return:
test=123
item=capture
Refiddle Demo
If you want to capture item=capture, it is straightforward:
/item=[^\/]*/
If you want to also extract the value,
/item=([^\/]*)/
If you only want to match the value, then you need to use a look-behind.
/(?<=item=)[^\/]*/
EDIT: too many errors due to insomnia. Also, screw PHP and its failure to disregard separators in a character group as separators.
Here is a function I wrote some time ago. I modified it a little, and added the $keys argument so that you can specify valid keys:
function getKeyValue($string, Array $keys = null) {
$keys = (empty($keys) ? '[\w\d]+' : implode('|', $keys));
$pattern = "/(?<=\/|$)(?P<key>{$keys})\s*=\s*(?P<value>.+?)(?=\/|$)/";
preg_match_all($pattern, $string, $matches, PREG_SET_ORDER);
foreach ($matches as & $match) {
foreach ($match as $key => $value) {
if (is_int($key)) {
unset($match[$key]);
}
}
}
return $matches ?: FALSE;
}
Just trow in the string and valid keys:
$string = 'somestring.bla/test=123/ohboy/item/item=capture';
$keys = array('test', 'item');
$keyValuePairs = getKeyValue($string, $keys);
var_dump($keyValuePairs);

Categories