print random string from string with multiply words - php

I am new to php and trying out some different things.
I got a problem with printing a random value from a string from multiply values.
$list = "the weather is beautiful tonight".
$random = one random value from $list, for example "beautiful" or "is"
Is there any simple way to get this done?
Thanks!

well, as #Dagon suggested, you can use explode() to get an array of strings, then you can use rand($min, $max) to get an integer between 0 and the length of your array - 1. and then read the string value inside your array at the randomly generated number position.

// First, split the string on spaces to get individual words
$arg = explode(' ',"the weather is beautiful tonight");
// Shuffle the order of the words
shuffle($arg);
// Display the first word of the shuffled array
print $arg[0];

Related

PHP count instances of array items in a string

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

Getting 2 random letters sequentially from a string

So getting 2 random letters from a string is easy enough to find an answer to:
$var1 = substr(str_shuffle(str_repeat($var1, 2)), 0, 2);
But what if you want to get 2 letters sequentially from a string,Is there a way to do it without using a loop?
For instance, if you have a string named "Colorado", and if the first random character grabbed was "r", it would only get a letter from the remaining 3 letters for the 2nd chosen letter.
There is most likely other ways, here is one.
Pick random char, use stristr, shuffle it then grab first 2 chars.
<?php
$var = 'Colorado';
// pick random
$picked = $var[rand(0, strlen($var))];
// grab string after first occurrence
$parts = stristr($var, $picked);
// shuffle it
$part = str_shuffle($parts);
echo $part[0].$part[1];
https://3v4l.org/uDvRX
*your need to add some undefined checks to handle no matches etc

Php number out of text?

Im new here. I need help with php.
$FullDescriptionLine = Model 23MP48HQ-P|23"|Panel IPS|Resolution 1920x1080|Form factor 16:9|
how can i get 23" out of that string?
Thank you
Martin
Use PHP's explode function to split the string on pipes (|), then get the second index (1 in computer indexes) of that array.
$FullDescriptionLine = 'Model 23MP48HQ-P|23"|Panel IPS|Resolution 1920x1080|Form factor 16:9|';
echo explode('|', $FullDescriptionLine)[1];
Online PHP demo
Just explode() it with pipe | character and grab the first i.e 1st index as array starts from 0 index.
<?php
$FullDescriptionLine = 'Model 23MP48HQ-P|23"|Panel IPS|Resolution 1920x1080|Form factor 16:9|';
$array = explode('|',$FullDescriptionLine);
//just for debug and clearly understand it
print '<pre>';
print_r($array);
print '</pre>';
echo $array[1];
?>
DEMO: https://3v4l.org/8aGuO
For structured strings I recommend str_getcsv and then use the second parameter to define the delimiter.
$array = str_getcsv('Model 23MP48HQ-P|23"|Panel IPS|Resolution 1920x1080|Form factor 16:9|', '|');
echo $array[1];
https://3v4l.org/7XSDQ
You can use explode function. It converts a given string into array elements, separated by a delimiter. It takes two inputs, a delimiter string ('|') and the string to convert into array chunks ($FullDescriptionLine).
Now, in your case, 23" is in the second substring (array index 1 - remember that array indexing start from 0). Post exploding the string, you can get the value using index [1].
Try the following (Rextester DEMO):
$FullDescriptionLine = 'Model 23MP48HQ-P|23"|Panel IPS|Resolution 1920x1080|Form factor 16:9|';
// explode the string and access the value
$result = explode('|', $FullDescriptionLine)[1];
echo $result; // displays 23"
Using explode() is simple and good that multiple user posted it. But there is another way. Using regex in preg_match()
preg_match("/\|([^|]+)/", $FullDescriptionLine, $matches);
echo $matches[1];
Check result in demo

php max function returns min value from array

this is my first post. sorry if i did something wrong...
anyways i have a file that gets updates by php and this is EXACTLY it:
31\n
127\n
131\n
124\n
144\n
142\n
133\n
133\n
9\n
0\n
22\n
18\n
i made this script in php:
$logContents = file_get_contents("logs/mainlog.txt");
$logitemArray = explode("\n", $logContents);
echo max($logitemArray);
but it echos 9. why? it said in the php documentation that max() should return the biggest value in the array
thanks in advance
explode() returns an array of strings, so they're being compared lexicographically. You need to convert them to numbers so that max() will compare them numerically.
$logitemArray = array_map('intval', explode("\n", $logContents));
echo max($logitemArray);
BTW, you can use the file() function to read a file directly into an array of lines, instead of using file_get_contents() followed by explode().
$logitemArray = array_map('intval', file("logs/mainlog.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
Like the comments have said, it's because 9 is the largest lexigraphical value. If it said 900 it would still be the same.
This is because when you split the string with explode you get an array of type string. The following code will convert the elements in the array to integers which should give expected behaviour.
$logitemArray = array_map('intval', explode("\n", $logContents));

how to replace space of a string with "," and convert into array

I have a text box.
I am enter the value in text box like 12 13 14.
and i am want to convert this into 12,13,14 and then convert it into array and show each separate value.
If your form field asks for the values without a comma, then you will need to explode the POST data by space. What you're doing now is imploding it by comma (you can't implode a string to begin with), and then trying to pass that into a foreach loop. However, a foreach loop will only accept an array.
$ar = explode(' ',$da);
That simple change should fix it for you. You will want to get rid of the peculiar die() after your foreach (invalid syntax, and unclear what you're trying to do there!), and validate your data before the loop instead. By default, if you explode a string and no matching delimiters are found, the result will be an array with a single key, which you can pass into a loop without a problem.
Are you sure you want to expect the user enters data in that particular format? I mean, what if the user uses more than one space character, or separate the numbers actually with commas? or with semicolons? or enters letters instead of numbers? Anyway.. at least you could transform all the spaces to a single space character and then do the explode() as suggested:
$da = trim(preg_replace('/\s+/', ' ', $_POST['imp']));
$ar = explode(' ', $da);
before your foreach().
use explode instead of implode as
The explode() function breaks a string into an array.
The implode() function returns a string from the elements of an array.
and you cannot do foreach operation for a string.
$da=$_POST['imp'];
$ar = explode(' ',$da);
foreach($ar as $k)
{
$q="insert into pb_100_fp (draw_3_fp) values ('".mysqli_real_escape_string($conn, $k)."')";
$rs=mysqli_query($conn, $q);
echo $k.",";
}
then you will get this output
o/p : 12,13,14,

Categories