This question already has answers here:
How do I check if a string contains a specific word?
(36 answers)
Closed 7 years ago.
I have the following string in PHP:
$cars = "Ford Chevrolet Dodge Chrysler";
I am required to output which words have various properties such as: Which word ends in 'let'? Or which word starts with 'Fo'?
I am unsure how to approach this. I am familiar enough with regex formatting, and I have gotten my preg_match to identify matches, but that's only results given in 1 or 0.
So should I split up the words using the space as a delimiter and search each one for matches individually? Or is there a simpler way of going about this?
I am aware of the preg_split function, but I don't know how to actually access the split strings.
$cars = "Ford Chevrolet Dodge Chrysler";
$param1 = '/(let)+/';
$param2 = '/(fo)+/';
echo preg_match($param1, $cars);
echo preg_match($param2, $cars);
I am aware that this doesn't work, but it prints 1s and verifys to me that matches are being found for both parameters. I just don't know how to extract the full 'Chevrolet' and full 'Ford' for parameter 1 and 2 respectively.
I am sure you're going to be able to figure out how to insert user input into variables $start or $end – just in case: ask them if they want the input string at the beginning or at the end, and based on the answer, save the string to search in to either $start or $end.
$string = "Ford Chevrolet Dodge Chrysler";
$start = "";
$end = "let";
if(!empty($start))
preg_match_all("#" . $start . "\w+#", $string, $matches);
elseif(!empty($end))
preg_match_all("#\w+" . $end ."#", $string, $matches);
else
die("Nothing has been set!");
print_r($matches);
This is the case implemented for all the words ending with a let in your example string. Bear in mind the regex is only going to match word characters. If you're going to get more complicated strings, maybe another solution should be created.
To simply echo all the matches, use foreach loop like this instead of the print_r function:
if(!empty($matches))
{
foreach($matches as $match)
echo $match . "<br>";
}
else
die("Nothing matched!");
Related
I am trying to replace strings contains specific string including a dynamic number in between.
I tried preg_match_all but it give me NULL value
Here is what i am actually looking for with all details:
In my long text there are values which contains this [_wc_acof_(some dynamic number)] , i.e: [_wc_acof_6] i want to convert them to $postmeta['_wc_acof_14'][0]
This can be multiple in the same long text.
I want to run through with this logic:
1- First i get all numbers after [_wc_acof_ and save them in array by using preg_match_all as guided here get number after string php regex
2- Then i run a foreach loop and set my arrays for patterns and replacements with that number i.e:
foreach ($allMatchNumbers as $MatchNumber){
$key = "[_wc_acof_" . $MatchNumber. "]";
$patterns[] = $key;
$replacements[] = $postmeta[$key][0];
}
3- Then i do replace with this echo preg_replace($patterns, $replacements, $string);
But i am unable to get preg_match_all it gives me NULL where i tried below
preg_match_all('/[_wc_acof_/',$string,$allMatchNumbers );
Please Help? i am not sure if preg_grep is better than this?
It seems you want to process the input in stages, to obtain all the numbers in specific lexical context first, and then modify the user input using some lookup technique.
The first step can be implemented as
preg_match_all('~\[_wc_acof_(\d+)]~', $text, $matches)
that extracts all sequences of one or more digit in between [_wc_acof_ and ] into Group 1 (you can access the values via $matches[1]).
Then, you may fill the $replacements array using these values.
Next, you can use
preg_replace_callback('~\[_wc_acof_(\d+)]~', function($m) use ($replacements){
return $replacements[$m[1]];
}, $text)
See the PHP demo:
<?php
$text = '<p>[_wc_acof_6] i want to convert this and it contains also this [_wc_acof_9] or can be this [_wc_acof_11] number can never be static</p>';
if (preg_match_all('~\[_wc_acof_(\d+)]~', $text, $matches)) {
foreach($matches[1] as $matched){
$replacements[$matched] = 'NEW_VALUE_FOR_'.$matched.'_KEY';
}
print_r($replacements);
echo preg_replace_callback('~\[_wc_acof_(\d+)]~', function($m) use ($replacements){
return $replacements[$m[1]];
}, $text);
}
Output:
Array
(
[0] => 6
[1] => 9
[2] => 11
)
NEW_VALUE_FOR_6_KEY i want to convert this and it contains also this NEW_VALUE_FOR_9_KEY or can be this NEW_VALUE_FOR_11_KEY number can never be static
In PHP 7.3:
Given this array of low relevancy keywords...
$low_relevancy_keys = array('guitar','bass');
and these possible strings...
$keywords_db = "red white"; // desired result 0
$keywords_db = "red bass"; // desired result 1
$keywords_db = "red guitar"; // desired result 1
$keywords_db = "bass guitar"; // desired result 2
I need to know the number of matches as described above. A tedious way is to convert the string to a new array ($keywords_db_array), loop through $keywords_db_array, and then loop through $low_relevancy_keys while incrementing a count of matches. Is there a more direct method in PHP?
The way you described in your question but using array_* functions:
echo count(array_intersect(explode(' ', $keywords_db), $low_relevancy_keys));
(note that you can replace explode with preg_split if you need to be more flexible)
or using preg_match_all (that returns the number of matches):
$pattern = '~\b' . implode('\b|\b', $low_relevancy_keys) . '\b~';
echo preg_match_all($pattern, $keywords_db);
demo
I am going to parse a log file and I wonder how I can convert such a string:
[5189192e][game]: kill killer='0:Tee' victim='1:nameless tee' weapon=5 special=0
into some kind of array:
$log['5189192e']['game']['killer'] = '0:Tee';
$log['5189192e']['game']['victim'] = '1:nameless tee';
$log['5189192e']['game']['weapon'] = '5';
$log['5189192e']['game']['special'] = '0';
The best way is to use function preg_match_all() and regular expressions.
For example to get 5189192e you need to use expression
/[0-9]{7}e/
This says that the first 7 characters are digits last character is e you can change it to fits any letter
/[0-9]{7}[a-z]+/
it is almost the same but fits every letter in the end
more advanced example with subpatterns and whole details
<?php
$matches = array();
preg_match_all('\[[0-9]{7}e\]\[game]: kill killer=\'([0-9]+):([a-zA-z]+)\' victim=\'([0-9]+):([a-zA-Z ]+)\' weapon=([0-9]+) special=([0-9])+\', $str, $matches);
print_r($matches);
?>
$str is string to be parsed
$matches contains the whole data you needed to be pared like killer id, weapon, name etc.
Using the function preg_match_all() and a regex you will be able to generate an array, which you then just have to organize into your multi-dimensional array:
here's the code:
$log_string = "[5189192e][game]: kill killer='0:Tee' victim='1:nameless tee' weapon=5 special=0";
preg_match_all("/^\[([0-9a-z]*)\]\[([a-z]*)\]: kill (.*)='(.*)' (.*)='(.*)' (.*)=([0-9]*) (.*)=([0-9]*)$/", $log_string, $result);
$log[$result[1][0]][$result[2][0]][$result[3][0]] = $result[4][0];
$log[$result[1][0]][$result[2][0]][$result[5][0]] = $result[6][0];
$log[$result[1][0]][$result[2][0]][$result[7][0]] = $result[8][0];
$log[$result[1][0]][$result[2][0]][$result[9][0]] = $result[10][0];
// $log is your formatted array
You definitely need a regex. Here is the pertaining PHP function and here is a regex syntax reference.
I know there are lots of tutorials and question on replacing something in a string.
But I can't find a single one on what I want to do!
Lets say I have a string like this
$string="Hi! [num:0]";
And an example array like this
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
Now what I want is that PHP should first search for the pattern like [num:x] where x is a valid key from the array.
And then replace it with the matching key of the array. For example, the string given above should become: Hi! na
I was thinking of doing this way:
Search for the pattern.
If found, call a function which checks if the number is valid or not.
If valid, returns the name from the array of that key like 0 or 1 etc.
PHP replaces the value returned from the function in the string in place of the pattern.
But I can't find a way to execute the idea. How do I match that pattern and call the function for every match?
This is just the way that I am thinking to do. Any other method will also work.
If you have any doubts about my question, please ask in comments.
Try this
$string="Hi! [num:0]";
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
echo preg_replace('#(\!)?\s+\[num:(\d+)\]#ie','isset($array[\2]) ? "\1 ".$array[\2]["name"] : " "',$string);
If you don't want the overhead of Regex, and your string format remains same; you could use:
<?php
$string="Hi! [num:0]";
echo_name($string); // Hi John
echo "<br />";
$string="Hello! [num:10]";
echo_name($string); // No names, only Hello
// Will echo Hi + Name
function echo_name($string){
$array=array();
$array[0]=array('name'=>"John");
$array[1]=array('name'=>"Doe");
$string = explode(" ", $string);
$string[1] = str_replace("[num:", "", $string[1]);
$string[1] = str_replace("]", "", $string[1]);
if(array_key_exists($string[1], $array)){
echo $string[0]." ".$array[$string[1]]["name"];
} else {
echo $string[0]." ";
}
}// function echo_sal ENDs
?>
Live: http://codepad.viper-7.com/qy2uwW
Assumptions:
$string always will have only one space, exactly before [num:X].
[num:X] is always in the same format.
Of course you could skip the str_replace lines if you could make your input to simple
Hi! 0 or Hello! 10
I have a list of items that are in this format:
05/01 – Some Basic: Text Here (Alpha, Bravo, Charli)
The first part is a date, then its always followed by a - . Then some text which represents a title or location of some sort and then some keywords that may or may not be in the parentheses.
I want to be able to extract the $month the $day the $title (including any colons) and the $keyword1 $keyword2 $keyword3 if they are there. Then assign them all to individual variables like the ones I've created so I can add them into my database. Getting it to do one of these at a time would be a great start but ultimately I want to be able to paste in multiple items in that format(without any spaces or characters to mark the difference besides whats already there) and be able to bulk extract them.
I've tried to use Preg_Match_all and things like stristr() but am having difficulty. I don't really understand how to use them to get the specific parts.
For example
$month = stristr($listItem, '/', true);
echo"$month<br />";
$preDay = stristr($listItem, 'The', true);
echo"$preDay<br />";
$day = stristr($preDay, '/', false);
echo"$day<br />";
This only outputs this:
05
05/01 –
/01 –
^ I can't have the / or any weird –.
Actual code and an explanation of how to do this would be awesome! If you are using pregmatch I would really appreciate a breakdown of how your filtering this. Thank you much.
The easiest way is using explode().
The explode() function provides a fast way to break strings into arrays. See the manual: http://php.net/manual/pt_BR/function.explode.php
With this format of string, you can break it into an array as follows.
$string = '05/01 - Some Basic: Text Here (Alpha, Bravo, Charli)';
$array = explode('-',$string);
$date = $array[0]; //Date 05/01
$array= explode('(',$array[1]);
$title = $array[0];
$tags = $array[1];
//Now you have
$date = '05/01';
$title = 'Some Basic: Text Here';
$tags = 'Alpha, Bravo, Charli)';
//Notice that the first parenthesis of tags was exploded.
//This is valid if and only if you have your string in the format
// [date] - [title] ([tags]
I don't know if this is the best way but it works. You can also try using preg_split() function. This function makes a split using regular expressions. If you need help on regular expressions see http://www.phpf1.com/tutorial/php-regular-expression.html
EDIT 1 I noticed that you string contains this symbol "–" after the date. This is not a hyphen as I know it. I use the minus signal to write it on my keyboard.
Your simbol / mine = –-
They are a little bit different.