Array of strings from the most common function - php

I am trying to call each string from an array. However, I am using this code to generate the array.
function extract_common_words($string, $stop_words, $max_count = 5) {
$string = preg_replace('/ss+/i', '', $string);
$string = trim($string); // trim the string
$string = preg_replace('/[^a-zA-Z -]/', '', $string); // Only take alphabet characters, but keep the spaces and dashes too…
$string = strtolower($string); // Make it lowercase
preg_match_all('/\b.*?\b/i', $string, $match_words);
$match_words = $match_words[0];
foreach ( $match_words as $key => $item ) {
if ( $item == '' || in_array(strtolower($item), $stop_words) || strlen($item) <= 3 ) {
unset($match_words[$key]);
}
}
$word_count = str_word_count( implode(" ", $match_words) , 1);
$frequency = array_count_values($word_count);
arsort($frequency);
//arsort($word_count_arr);
$keywords = array_slice($frequency,0);
return $keywords;
}
It returns an array which I can't seem to get the STRINGS from. So, I want to essentially take the results, and place them in a list which is an array of strings, with each string being the words, in consecutive order from most common to least common.

You can use the strtok function. Or else you can explode the string by whitespace. I hope that helps :)

Related

How to explode string into array with index in php? [duplicate]

This question already has answers here:
Explode a string to associative array without using loops? [duplicate]
(10 answers)
Closed 7 months ago.
I have a PHP string separated by characters like this :
$str = "var1,'Hello'|var2,'World'|";
I use explode function and split my string in array like this :
$sub_str = explode("|", $str);
and it returns:
$substr[0] = "var1,'hello'";
$substr[1] = "var2,'world'";
Is there any way to explode $substr in array with this condition:
first part of $substr is array index and second part of $substr is variable?
example :
$new_substr = array();
$new_substr["var1"] = 'hello';
$new_substr["var2"] = 'world';
and when I called my $new_substr it return just result ?
example :
echo $new_substr["var1"];
and return : hello
try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$array = [];
foreach ($sub_str as $string) {
$data = explode(',', $string);
if(isset($data[0]) && !empty($data[0])){
$array[$data[0]] = $data[1];
}
}
You can do this using preg_match_all to extract the keys and values, then using array_combine to put them together:
$str = "var1,'Hello'|var2,'World'|";
preg_match_all('/(?:^|\|)([^,]+),([^\|]+(?=\||$))/', $str, $matches);
$new_substr = array_combine($matches[1], $matches[2]);
print_r($new_substr);
Output:
Array (
[var1] => 'Hello'
[var2] => 'World'
)
Demo on 3v4l.org
You can do it with explode(), str_replace() functions.
The Steps are simple:
1) Split the string into two segments with |, this will form an array with two elements.
2) Loop over the splitted array.
3) Replace single quotes as not required.
4) Replace the foreach current element with comma (,)
5) Now, we have keys and values separated.
6) Append it to an array.
7) Enjoy!!!
Code:
<?php
$string = "var1,'Hello'|var2,'World'|";
$finalArray = array();
$asArr = explode('|', $string );
$find = ["'",];
$replace = [''];
foreach( $asArr as $val ){
$val = str_replace($find, $replace, $val);
$tmp = explode( ',', $val );
if (! empty($tmp[0]) && ! empty($tmp[1])) {
$finalArray[ $tmp[0] ] = $tmp[1];
}
}
echo '<pre>';print_r($finalArray);echo '</pre>';
Output:
Array
(
[var1] => Hello
[var2] => World
)
See it live:
Try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$new_str = array();
foreach ( $sub_str as $row ) {
$test_str = explode( ',', $row );
if ( 2 == count( $test_str ) ) {
$new_str[$test_str[0]] = str_replace("'", "", $test_str[1] );
}
}
print $new_str['var1'] . ' ' . $new_str['var2'];
Just exploding your $sub_str with the comma in a loop and replacing single quote from the value to provide the expected result.

how to filter out invisible characters from string

I have copied some item manually from web pasted into txt and then stored it into database.Now what I missed is invisible characters.
when I'm retrieving first characters of each word using different values in substr($word,0,x) it shows presence of invisible characters.
php code-
public function getPrefixAttribute()
{
$str=$this->attributes['Subject_name'];
$exclude=array('And', 'of','in');
$ret = '';
foreach (explode(' ', $str) as $word)
{
if(in_array($word, $exclude))
{continue;}
else{
$ret .= strtoupper(substr($word,0,1));}
}
return $ret;
}
output-
substr($word,0,1)
string-'data structures and algorithms'
output-'SA'
expected-'DSA'
string-'Web Development'
output-'WD'
substr($word,0,2)
string-'data structures and algorithms'
output-'DSTAL'
expected-'DASTAL'
string-'Web Development'
output-'WEDE'
You are almost there:
<?php
public function getPrefixAttribute()
{
$str = $this->attributes[ 'Subject_name' ];
// Make these uppercase for easier comparison
$exclude = array( 'AND', 'OF', 'IN' );
$ret = '';
foreach( explode( ' ', $str ) as $word )
{
// This word should have a length of 1 or more or else $word[ 0 ] will fail
// Check its uppercase version against the $exclude array
if( strlen( $word ) >= 1 && !in_array( strtoupper( $word ) , $exclude ) )
{
$ret.= strtoupper( $word[ 0 ] );
}
}
return $ret;
}
You can use the array_ methods to do a lot of the work (details in comments in code)...
public function getPrefixAttribute()
{
$str=$this->attributes['Subject_name'];
// Use uppercase list of words to exclude
$exclude=array('AND', 'OF', 'IN');
// Split string into words (uppercase)
$current = explode(" ", strtoupper($str));
// Return the difference between the string words and excluded
// Use array_filter to remove empty elements
$remain = array_filter(array_diff($current, $exclude));
$ret = '';
foreach ($remain as $word)
{
$ret .= $word[0];
}
return $ret;
}
Using array_filter() removes any empty elements, these can cause the [0] part to fail and aren't useful anyway. This can happen if you have double spaces as it will assume an empty element.
Another approach would be to use inbuilt PHP functions:-
function getPrefixAttribute() {
$str = $this->attributes['Subject_name']; // 'data Structures And algorithms';
$exclude = array('and', 'of', 'in'); // make sure to set all these to lower case
$exploded = explode(' ', strtolower($str));
// get first letter of each word from the cleaned array(without excluded words)
$expected_letters_array = array_map(function($value){
return $value[0];
}, array_filter(array_diff($exploded, $exclude)));
return strtoupper(implode('', $expected_letters_array));
}
The invisible characters are '/n','/r','/t'
and method for manually removing them is
$string = trim(preg_replace('/\s\s+/', ' ', $string));

Converting an array into a string

I am doing an assignment on how to take a string of text separated by commas and reverse the individual words and return the words in the same order.
This code does that but it is not returning it as a string for some reason and i do not understand.
<?php
function bassAckwards($input)
{
// YOUR CODE HERE
$commas = substr_count($input, ",");
$NumWords = ($commas + 1);
$words = array($input);
for($x=0;$x<$NumWords;$x++)
{
$answer = array(strrev($words[$x]));
$answer = implode(",",$answer);
print $answer;
}
}
?>
function bassAckwards($str){
$words = explode(',', $str);
$reversedWords = array_map('strrev', $words);
return implode(',', $reversedWords);
}
var_dump(bassAckwards('foo,bar,baz')); // string(11) "oof,rab,zab"
Save yourself some headaches and use the built-it functions.
explode
make 'foo,bar,baz' => array('foo','bar','baz')
array_map & strrev
Execute strrev (string reverse) on every element of the array with array_map and return the [modified] array back.
implode
convert the array back to a csv.
$reversedWords = array();
// Explode by commas
$words = explode(',', $input);
foreach ($word in $words) {
// For each word
// Stack it, reversed, in the new array $reversedWords
$reversedWords[] = strrev($word);
}
// Implode by commas
$output = implode(',', $reversedWords);
print $output;

How can I convert a string to an array, matching multiple delimiters using Preg_match in PHP?

I have the following possible strings:
NL DE
NL,DE
nl DE
nl de
NL/DE
NL,mismatch,DE
I'm looking for the preg_match that produces the following output given the inputs above.
array(
[0]=>"NL",
[1]=>"DE"
);
I've tried the following code:
preg_match_all('/(\w{2,2})/ui', $info["country"], $m);
but that seems to also cut up the word mismatch, which is undesired.
The regex should only match two letter country codes, everything else should be ignored.
How can I do this using preg_match in PHP?
Here's how you explode the string:
$string = 'NL DE
NL,DE
nl DE
nl de
NL/DE
NL,mismatch,DE';
Using explode and filter:
$string = explode("\n",str_replace(array(",","/"," ","\r"), "\n", strtoupper($string)));
$string = array_unique(array_filter($string,function($v){$v = trim($v); return strlen($v) === 2;}));
var_dump($string);
If you want to play around with the string, try this:
$s = ",\n\t \r";
$t = strtok(strtoupper($string), $s);
$l = array();
while ( $t !== false ) {
in_array($t, $l) OR strlen($t) == 2 AND $l[] = $t AND $t = strtok($s);
}
var_dump($l);
Output:
array
0 => string 'NL' (length=2)
1 => string 'DE' (length=2)
// #claudrian Variant
function SplitCountries($string){
// Sanity check
if(!is_string($string)) return false;
// Split string by non-letters (case insensitive)
$slices = preg_split('~[^a-z]+~i', trim($string));
// Keep only 2-letter words
$slices = preg_grep('~^[a-z]{2}$~i', $slices);
// Keep uniques
$slices = array_unique($slices);
// Done
return $slices;
}
// #Wiseguy Variant
function SplitCountries($string){
// Sanity check
if(!is_string($string)) return false;
// Capture only two letter packs
if(!preg_match_all('~\\b[a-z]{2}\\b~i', trim($string), $slices)){
return false;
}
// Keep uniques
$slices = array_unique($slices[0]);
// Done
return $slices;
}
Hope it helps.
This should work
$result = array();
preg_match_all('/([a-z]{2})(?:.*)?([a-z]{2})/i',$text, $matches);
$result = array( strtolower( $matches[1][0] ), strtolower( $matches[2][0] ) );
You'll have the results in the $result array

Replace all substring instances with a variable string

If you had the string
'Old string Old more string Old some more string'
and you wanted to get
'New1 string New2 more string New3 some more string'
how would you do it?
In other words, you need to replace all instances of 'Old' with variable string 'New'.$i. How can it be done?
An iterative solution that doesn't need regular expressions:
$str = 'Old string Old more string Old some more string';
$old = 'Old';
$new = 'New';
$i = 1;
$tmpOldStrLength = strlen($old);
while (($offset = strpos($str, $old, $offset)) !== false) {
$str = substr_replace($str, $new . ($i++), $offset, $tmpOldStrLength);
}
$offset in strpos() is just a little bit micro-optimization. I don't know, if it's worth it (in fact I don't even know, if it changes anything), but the idea is that we don't need to search for $old in the substring that is already processed.
See Demo
Old string Old more string Old some more string
New1 string New2 more string New3 some more string
Use preg_replace_callback.
$count = 0;
$str = preg_replace_callback(
'~Old~',
create_function('$matches', 'return "New".$count++;'),
$str
);
From the PHP manual on str_replace:
Replace all occurrences of the search string with the replacement string
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
search
The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
replace
The replacement value that replaces found search values. An array may be used to designate multiple replacements.
subject
The string or array being searched and replaced on, otherwise known as the haystack.
If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.
count
If passed, this will be set to the number of replacements performed.
Use:
$str = 'Old string Old more string Old some more string';
$i = 1;
while (preg_match('/Old/', $str)) {
$str = preg_replace('/Old/', 'New'.$i++, $str, 1);
}
echo $str,"\n";
Output:
New1 string New2 more string New3 some more string
I had some similar solution like KingCrunch's, but as he already answered it, I was wondering about a str_replace variant with a callback for replacements and came up with this (Demo):
$subject = array('OldOldOld', 'Old string Old more string Old some more string');
$search = array('Old', 'string');
$replace = array(
function($found, $count) {return 'New'.$count;},
function($found, $count) {static $c=0; return 'String'.(++$c);}
);
$replace = array();
print_r(str_ureplace($search, $replace, $subject));
/**
* str_ureplace
*
* str_replace like function with callback
*
* #param string|array search
* #param callback|array $replace
* #param string|array $subject
* #param int $replace_count
* #return string|array subject with replaces, FALSE on error.
*/
function str_ureplace($search, $replace, $subject, &$replace_count = null) {
$replace_count = 0;
// Validate input
$search = array_values((array) $search);
$searchCount = count($search);
if (!$searchCount) {
return $subject;
}
foreach($search as &$v) {
$v = (string) $v;
}
unset($v);
$replaceSingle = is_callable($replace);
$replace = $replaceSingle ? array($replace) : array_values((array) $replace);
foreach($replace as $index=>$callback) {
if (!is_callable($callback)) {
throw new Exception(sprintf('Unable to use %s (#%d) as a callback', gettype($callback), $index));
}
}
// Search and replace
$subjectIsString = is_string($subject);
$subject = (array) $subject;
foreach($subject as &$haystack) {
if (!is_string($haystack)) continue;
foreach($search as $key => $needle) {
if (!$len = strlen($needle))
continue;
$replaceSingle && $key = 0;
$pos = 0;
while(false !== $pos = strpos($haystack, $needle, $pos)) {
$replaceWith = isset($replace[$key]) ? call_user_func($replace[$key], $needle, ++$replace_count) : '';
$haystack = substr_replace($haystack, $replaceWith, $pos, $len);
}
}
}
unset($haystack);
return $subjectIsString ? reset($subject) : $subject;
}

Categories