PHP string words to array [closed] - php

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to take only full words from a string i mean full words = words with more then 4 chars.
Example of a string:
"hey hello man are you going to write some code"
I need to return to:
"hello going write some code"
Also i need to trim all of these words and put them into a simple array.
Is it possible?

You could use a regular expression to do it.
preg_replace("/\b\S{1,3}\b/", "", $str);
You could then put them into an array with preg_split().
preg_split("/\s+/", $str);

Use str_word_count() http://php.net/manual/fr/function.str-word-count.php
str_word_count($str, 1)
Will return you a list of words, then count the ones with more than n letters using strlen()
The big advantage of using str_word_count() over other solutions such as preg_match or explode is that it will account for the punctuation and discard it from the final list of words.

Depending on your full requirements and if you need the string array unmodified too, you could use explode for this, something like this would get your words into an array:
$str = "hey hello man are you going to write some code";
$str_arr = explode(' ', $str);
Then you can use array_filter to remove the words you don't want, like so:
function min4char($word) {
return strlen($word) >= 4;
}
$final_str_array = array_filter($str_arr, 'min4char');
Otherwise if you don't need the unmodified array, you can use a regular expression to get all matches that are above a certain length using preg_match_all, or replace out the ones that are using preg_replace.
One final option would be to do it the basic way, use explode to get your array as per the first code example, and then loop over everything using unset to remove the entry from the array. But then, you'd also need to reindex (depending on your subsequent usage of the 'fixed' array), which could be inefficient depending on how large your array is.
EDIT: Not sure why there are claims that it does not work, see below for output of var_dump($final_str_array):
array(5) { [1]=> string(5) "hello" [5]=> string(5) "going" [7]=> string(5) "write" [8]=> string(4) "some" [9]=> string(4) "code" }
#OP, to convert this back to your string, you can simply call implode(' ', $final_str_array) to get this output:
hello going write some code

First, put them into an an array:
$myArr = explode(' ', $myString);
Then, loop through and assign only those with a length of 4 or greater to a new array:
$finalArr = array();
foreach ($myArr as $val) {
if (strlen($val) > 3) {
$finalArr[] = $val;
}
}
Obviously, if you have commas and other special characters in your string, it gets trickier, but for a basic design, I think this gets you moving in the right direction.

$strarray = explode(' ', $str);
$new_str = '';
foreach($strarray as $word){
if(strlen($word) >= 4)
$new_str .= ' '.$word;
}
echo $new_str;
Code Output

No loops required, no nested function calls, no temporary arrays. Just 1 function call and a very simple regex.
$string = "hey hello man are you going to write some code";
preg_match_all('/\S{4,}/', $string, $matches);
//Printing Values
print_r($matches[0]);
See it working

<?php
$word = "hey hello man are you going to write some code";
$words = explode(' ', $word);
$new_word;
foreach($words as $ws)
{
if(strlen($ws) > 4)
{
$new_word[] = $ws;
}
}
echo "<pre>"; print_r($new_word);
?>

You can use explode() and array_filter() with trim() + strlen() to achieve this. Try it and post your code if you're stuck.

Related

Find key of first row containing a partial word match while searching a sentence

Here is my issue:
$array = array(
"1" => array("fruit", "salad", "vegetable"),
"2" => array("beef", "meat", "sausage"),
"3" => array("chocolate", "cake", "bread")
);
$sentence = "I love big sausage";
$sentence could also be I love big sausageS.
I need to associate a sentence to a category, so I need to analyze the sentence and to return the ID of the subarray matching with the sentence. For example "2" in my example.
I'm looking for the solution with the best performance. I guess I have no other choice than "explode" the sentence and "foreach" it at a minimum.
The project uses PHP7 and if it can use amazing native functions it'll be great.
I think this is best I can do.
Foreach the array and use preg_grep to find matches.
I use str_replace to replace spaces with | that is used as "or" in regex.
foreach($array as $key => $sub){
if(preg_grep("/" . str_replace(" ", "|", $sentence) . "/" ,$sub )){
echo "Match in ". $key . "\n";
}
}
https://3v4l.org/BqkW2
To match your sussageS example you can reverse the search and add .*? in the grep.
$arrSent = explode(" ", $sentence);
foreach($array as $key => $sub){
if(preg_grep("/" . implode(".*?|", $sub) . ".*?/" , $arrSent))
{
echo "Match in ". $key . "\n";
}
}
https://3v4l.org/MJqrv
But this will also accept sussage_and_beans. If you only want to match if the word is in plural (an s added at the end). Change .*? to s.
But it will be case sensitive so sussageS as in your example will not work.
but with : if(preg_grep("/" . implode("s|", $sub) . "s/i" , $arrSent))
Should make it case insensitive.
If you explode your $sentence and use a whitespace as the delimiter you will get an array of words.
You could use array_filter to remove those arrays from $array by checking if the intersect contains 1 or more words using array_intersect.
Then you could return an array using array_keys to get all the id's which contain word(s) that are in you sentence.
$array = array (
"1" => array("fruit","salad","vegetable"),
"2" => array("beef","meat","sausage"),
"3" => array("chocolate","cake","bread")
);
$expl = explode(' ', "I love big sausage");
$array = array_filter($array, function($x) use ($expl) {
return count(array_intersect($expl, $x)) > 0;
});
var_dump(array_keys($array));
Demo
That would give you:
array(1) {
[0]=>
int(2)
}
The earlier answers are making the mistake of trying to search the array of "needles" with the exploded or piped words in the "haystack". This will not work when you modify "sausage" in your sentence to "sausageS" -- there is no needle that has an s after sausage, so even if you use a case-insensitive approach it will still fail.
Because you are seeking a solitary qualifying key, it makes the most sense to stop searching as soon as a match is found. This task requirement eliminates array_filter() and preg_grep() as best performers -- they will both keep scanning data until the input is exhausted instead of stopping as soon as a match is found.
Code: (Demo)
$needlestack = [
"1" => ["fruit", "salad", "vegetable"],
"2" => ["beef", "meat", "sausage"],
"3" => ["chocolate", "cake", "bread"]
];
// $haystack = "I love big sausage";
$haystack = "I love big sausageS";
$found = null;
foreach ($needlestack as $id => $needles) {
foreach ($needles as $needle) {
if (stripos($haystack, $needle) !== false) {
$found = $id;
break 2;
}
}
}
var_export($found); // 2
stripos() will perform case-insensitively AND will allow for partial word matching (which is desirable for matching sausageS to sausage). By using nested loops and stripos(), this approach does not waste time preparing strings that will be unused.

Pipe Delimited List with numbers into array PHP

In the database I'm working on there's a string like this
1-Test Response|9-DNC|
This can have up to 9 pipe delimited items.
What I'm looking for advice on is the best possible way to take this string and turn it into an array with the number as the key and the string as the value.
I really suck with Regex. Can someone point me in the right direction?
Since it's not your fault you have the DB structured this way, please accept my sincere condolences. It must be hell working with this. Meh.
Now, to the point. You do not need regex to work with this string. If you have a problem and you want to solve it with regex, you have two problems.
Instead, use explode().
$testString = "1-Test Response|9-DNC|";
$result = [];
$explodedByPipeString = explode("|", $testString);
foreach($explodedByPipeString as $k => $v)
{
$explodedByDashString = explode("-", $v);
if(is_numeric($explodedByDashString[0]))
{
$result[$explodedByDashString[0]] = $explodedByDashString[1];
}
}
var_dump($result);
This gives
array(2) {
[1]=>
string(13) "Test Response"
[9]=>
string(3) "DNC"
}
Here's how I went about it for anyone else wondering
$SurveyOptions = preg_match_all('/(\d+)-([^|]+)/',
$res['survey_response_digit_map'], $matches);
$finalArray = array_combine($matches[1], $matches[2]);
Pretty straight forward.
Assuming the delimters: - and | do not exist in the keys or values, here is another non-regex way to tackle the string:
Code: (Demo)
$string = '1-Test Response|9-DNC|';
$string = str_replace(['-', '|'], ['=', '&'], $string); // generates: 1=Test Response&9=DNC&
parse_str($string, $result);
var_export($result);
Output:
array (
1 => 'Test Response',
9 => 'DNC',
)

Remove All Text 2 Places After Decimal Place PHP

I'm trying to scrape a products price from a page, however unfortunately it's not in a nice clean div so I'm having to clear all the other junk.
Note: I have looked at several examples however they all assume you only have nice organised numbers in your variable, not raw HTML stuffed on the end.
An example of the string my variable may hold:
$2.87 <span>10% Off Sale</span>
I've played about with substr and sttrpos, read the manual and still can't figure it out on my own.
I want to just cut the string two digits after the first decimal place is found... No doubt it's extremely simple when you know how!
What I want to end up with:
$2.87
An example of the mess I've got myself into trying:
$whatIWant = substr($data, strrpos($data, ".") + 2);
Thanks in advance,
Try this solution:
<?php
$string = "$2.87 <span>10% Off Sale</span>";
$matches = array();
preg_match('/(\$\d+\.\d{2})/', $string, $matches);
var_dump($matches);
Output:
array(2) {
[0]=>
string(5) "$2.87"
[1]=>
string(5) "$2.87"
}
For more info (why result is array etc.) you should check PHP manual on preg_match() function: link
The below should grab the matches for you;
$pattern = '/(\$\d+\.\d{2})/';
$string = '$2.87 <span>10% Off Sale</span>';
$matches = array();
preg_match($pattern, $string, $matches);
Outputs:
Array ( [0] => $2.87 [1] => $2.87 )
There is def better way to do this. For a start, assuming the html structure that you have above will always be the same, you could do something like:
$var = "$85.25 <span>10% Off Sale</span>";
$spl = explode("<", $var);
echo $spl[0];

How to grab number after a word or symbol in PHP?

I want to grab a text with PHP just like for an example, There is a data "The apple=10" and I want to grab only the numbers from the data which looks exactly like that. I mean, the number's place would be after 'equals'.
and my problem is that the number from the source can be 2 or 3 characters or on the other word it is inconstant.
please help me to solve them :)
$string = "Apple=10 | Orange=3 | Banana=7";
$elements = explode("|", $string);
$values = array();
foreach($elements as $element)
{
$element = trim($element);
$val_array = explode("=", $element);
$values[$val_array[0]] = $val_array[1];
}
var_dump($values);
Output:
array(3) {
["Apple"]=> string(2) "10"
["Orange"]=> string(1) "3"
["Banana"]=> string(1) "7"
}
Hope thats how you need it :)
Well, php is a bit lazy about int conversion, so 12345blablabla can be converted to 12345:
$value = intval(substr($str, strpos($str, '=') + 1));
Of course, this is not the cleanest way but it is simple. If you want something cleaner, you could use a regexp:
preg_match ('#=([0-9]+)#', $str, $matches);
$value = intval($matches[1]) ;
Try the below code:
$givenString= "The apple=10";
$required_string = substr($givenString, strpos($givenString, "=") + 1);
echo "output = ".$required_string ; // output = 10
Using strpos() function, you can Find the position of the first occurrence of a substring in a string
and substr() function, Return part of a string.

A bit lost with preg_match regular expression

I'm a beginner in regular expression so it didn't take long for me to get totally lost :]
What I need to do:
I've got a string of values 'a:b,a2:b2,a3:b3,a4:b4' where I need to search for a specific pair of values (ie: a2:b2) by the second value of the pair given (b2) and get the first value of the pair as an output (a2).
All characters are allowed (except ',' which seperates each pair of values) and any of the second values (b,b2,b3,b4) is unique (cant be present more than once in the string)
Let me show a better example as the previous may not be clear:
This is a string: 2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,never:0
Searched pattern is: 5
I thought, the best way was to use function called preg_match with subpattern feature.
So I tried the following:
$str = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
$re = '/(?P<name>\w+):5$/';
preg_match($re, $str, $matches);
echo $matches['name'];
Wanted output was '5 minutes' but it didn't work.
I would also like to stick with Perl-Compatible reg. expressions as the code above is included in a PHP script.
Can anyone help me out? I'm getting a little bit desperate now, as Ive spent on this most of the day by now ...
Thanks to all of you guys.
$str = '2 minutes:2,51 seconds:51,5 minutes:5,10 minutes:10,15 minutes:51,never:0';
$search = 5;
preg_match("~([^,\:]+?)\:".preg_quote($search)."(?:,|$)~", $str, $m);
echo '<pre>'; print_r($m); echo '</pre>';
Output:
Array
(
[0] => 5 minutes:5
[1] => 5 minutes
)
$re = '/(?:^|,)(?P<name>[^:]*):5(?:,|$)/';
Besides the problem of your expression having to match $ after 5, which would only work if 5 were the last element, you also want to make sure that after 5 either nothing comes or another pair comes; that before the first element of the pair comes either another element or the beginning of the string, and you want to match more than \w in the first element of the pair.
A preg_match call will be shorter for certain, but I think I wouldn't bother with regular expressions, and instead just use string and array manipulations.
$pairstring = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
function match_pair($searchval, $pairstring) {
$pairs = explode(",", $str);
foreach ($pairs as $pair) {
$each = explode(":", $pair);
if ($each[1] == $searchval) {
echo $each[0];
}
}
}
// Call as:
match_pair(5, $pairstring);
Almost the same as #Michael's. It doesn't search for an element but constructs an array of the string. You say that values are unique so they are used as keys in my array:
$str = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
$a = array();
foreach(explode(',', $str) as $elem){
list($key, $val) = explode(':', $elem);
$a[$val] = $key;
}
Then accessing an element is very simple:
echo $a[5];

Categories