I have a sting that looks like this
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
I want to break out selected companies and the number of locations by comparing the first string to a second string like
$selectedstores = "‘F Mart’, 'J/M Store";
And output a sting like
$selectedwithnumber = "‘F Mart (6)’, 'J/M Store (17)'"
There could be 1 to 15 companies in a string and the location number varies but the apostrophes and parenthesis are standard. I hope there an easy way to do this as I have no idea where to start. Thanks in advance.
You can use explode function to split arrays to parts, and use preg_replace function to remove number of companies (with brackets) from first string. below you can find working example:
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
$selectedstores = "‘F Mart’, 'J/M Store'";
//split second array
$selectedArray = explode(', ', $selectedstores);
$resultArray = array();
//split first array
foreach(explode(', ', $storelist) as $storeWithNumber) {
//remove " (number)" from each part
$store = preg_replace('/\s+\(\d+\)/', '', $storeWithNumber);
//check if current part is on selected list
if (in_array($store, $selectedArray)) {
$resultArray[] = $storeWithNumber;
}
}
$selectedwithnumber = implode(', ', $resultArray);
echo $selectedwithnumber.PHP_EOL;
result is:
‘F Mart (6)’, 'J/M Store (17)'
This will get what you need based on your description. It breaks up your strings into arrays and then uses a nested foreach loop to do the comparisons. I used string functions over regular expression functions in case speed becomes an issue. It does however require that your main string of stores follows the conventions you described.
<?php
$storelist = "'F Mart (6)', 'ACME (5)', 'J/M Store (17)'";
$selectedstores = "'F Mart', 'J/M Store'";
$stores = explode(",", $storelist);
$selected = explode(",", $selectedstores);
$newStoreList = array();
foreach($selected as $selectedStore) {
foreach($stores as $store) {
$s = trim( $selectedStore, "' ");
if(strstr($store, $s)) {
$newStoreList[] = $store;
}
}
}
$newStoreList = implode(",", $newStoreList);
echo $newStoreList;
?>
This will output: 'F Mart (6)', 'J/M Store (17)'
Hope that helps!
Related
I'm running a query to display an array. After the array is displayed I'm using that in Google Maps so the array needs to read a specific way.
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
So my array has to read array', 'array', 'array because I echo the array into the address.
var addresses = ['<?php echo $namelist ?>'];
This is my code and it outputs 'array', 'array', 'array',
$resultsearch = $con->query("SELECT * FROM db") or die(mysqli_error());
$name = array();
while ($result = $resultsearch->fetch_object()) {
$name[] = $result->name;
$namelist = substr("'".implode($name)."', ", 0, -1);
If I change the 0, -1 to 1, -2 then I'm left with array' array' array' and so forth.
I literally need the remove 1 character from the end of string and 1 character at the beginning without altering the characters of the array.
Just to add that using implode(',', $name); did not display the ',' which is why I'm trying to find a work around.
Any ideas?
Your problems are:
You use implode(); in the wrong way: right is implode("', '",$names);
substr() will not work because of wrong use of implode().
Tip: Instead of using substr() just do rtrim('value',',');
To fix your code change it to this:
$name[] = "'{$result->name}'";
$namelist = implode(', ',$name);
or this
$name[] = $result->name;
$namelist = implode("', '",$name);
And this too:
var addresses = [<?php echo $namelist ?>];
to get proper javascript/json array data.
Also works:
var addresses = <?php echo json_encode($namelist); ?>;
But here you should not add ' single-quotes to the names when collecting into an array.
Have a nice day
I ended up with $namelist = "'".$result->name."'," and then echo $namelist;
My results were addresses and believe that implode(',', $name) wouldn't work because of the results.
i was writing this code to remove a list of values from a dynamic string key
//key
$chiave = "motore a scoppio di seconda generazione";
//sanitize string
//$chiave = pulisci($chiave);
//clean from double whitespaces
$chiave = preg_replace('/\s+/', ' ',$chiave);
//convert in lowercase
$chiave = strtolower($chiave);
//define array with all values to remove
$togliere = array("a","il","lo","la","egli","gli","li","di","do","e","è","alla","alle","&","un","uno","una");
$togliere2 = array("d'","l'");
//explode words
$keyval = explode(" ",$chiave);
//remove values
$keyvalclean = array_values(array_diff($keyval, $togliere));
//remove others values
$valori = array();
for($x=0; $x<=count($keyvalclean); $x++){
$valori[] = str_replace($togliere2,"",$keyvalclean[$x]);
}
//print the result
echo implode(" ",$valori);
this will output "motore scoppio seconda generazione"
there is a faster and optimized code to do that?
thanks
Your code looks okay to me. But you don't need to loop through the array to remove the values using str_replace(). This function can take an array as its argument and perform the replacement on each one of them in one go.
This:
$valori = array();
for($x=0; $x<=count($keyvalclean); $x++){
$valori[] = str_replace($togliere2,"",$keyvalclean[$x]);
}
can be changed to just:
$valori = str_replace($togliere2, "", $keyvalclean);
echo implode(" ",$valori);
Demo
Use str_replace()
You could insert an array to replaced by "" with this function.
Say I have a String 030512 Jack 25 Male\n030513 David 23 Male\n030514 ..., how to extract the info from this String as a two dimensional table in PHP?
In Java, I can use StringTokenizer, like:
StringTokenizer lineTokenizer = new StringTokenizer("030512 Jack ...", "\n");
List<Student> students = new ArrayList<Student>();
while(lineTokenizer.hasMoreTokens()) {
String line = lineTokenizer.nextToken();
StringTokenizer itemTokenizer = new StringTokenizer(line, " ");
String id = itemTokenizer.nextToken();
String name = itemTokenizer.nextToken();
String age = itemTokenizer.nextToken();
String sext = itemTokenizer.nextToken();
students.add(new Student(id, name, age, sex));
}
Actually, my final goal is extracting this "table-like" info and store them into a Mysql database.
I am not familiar with PHP, could you show me how to do this in PHP, or what is a good practice to implement this two-dimensional data insertion into a Mysql database?
You can use the explode or split functions. E.g.
$records = explode("\n", $raw_data);
foreach($record in $records) {
$fields = explode(" ", $record);
$id = fields[0];
$name = fields[1];
///....
}
Not fancy but easier to understand in my opinion (requires that the string doesn't end with newline though, and that the information is always correctly formatted):
$students = array();
//no newline at the end, or you'll have to add a check for that in the loop.
$str = "030512 Jack 25 Male\n030513 David 23 Male";
foreach(explode("\n", $str) as $student_str) {
list($id, $name, $age, $sex) = explode(" ", $student_str);
array_push($students, array(":id"=>$id,":name"=>$name, ":age"=>$age, ":sex"=>$sex));
}
//For the DB part which has been quite absent.
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$query = "INSERT INTO students (id, name, age, sex) VALUES (:id, :name, :age, :sex)";
$prepared_query = $conn->prepare($query);
foreach($students as $student) {
$prepared_query->execute($student);
}
You could of course execute the queries in the first loop instead if thats what you want.
You can use explode() coupled with list():
foreach (explode("\n", $yourString) as $line) {
list($id, $name, $age, $sex) = explode(' ', $line);
// ...
}
Edit:
Updated the solution to correct a misunderstanding of the original data structure.
You could do like this
$string = "030512 Jack 25 Male\n030513 David 23 Male\n030514";
$array = array_map(function($v) {
return explode(' ', $v);
}, explode("\n", $string));
I hope you can help me.
I have a string like the following
Luke 1:26-38
And I would like to be able to break it up into tokens or individual variables so that I can use the variables in an SQL query.
I've tried using explode, however I've only been able to make it explode on one character such as : or -
My string has : and - and also a space between the name and the first number.
My goal is to have:
$name = Luke;
$book = 1;
$from = 26;
$to = 38;
Is anyone able to help please.
Many thanks
You can do that with a simple string scanning (Demo):
$r = sscanf("Luke 1:26-38", "%s %d:%d-%d", $name, $book, $from, $to);
The varibales then contain the information. %s represents a string (without spaces), %d a decimal. See sscanf.
To make this "bible safe", it needs some additional modifications:
$r = sscanf($string, "%[ a-zA-Z] %d:%d-%d", $name, $book, $from, $to);
$name = trim($name);
(Second demo).
list( $name, $book, $from, $to ) = preg_split( '/[ :-]/', 'Luke 1:26-38' );
echo $name; //"Luke"
/* Split results in an Array
(
[0] => Luke
[1] => 1
[2] => 26
[3] => 38
)
*/
$string = "Luke 1:26-38";
preg_match('#^(\w+)\s(\d+):(\d+)-(\d+)$#', $string, $result);
print_r($result);
regex is hard to configure for this because of the multiple configurations of bible book names, chapter and verse num. Because some books begin with a number and some books have multiple spaces in the book names.
I came up with this for building a sql query, it works for these passage search types..
(John), (John 3), (Joh 3:16), (1 Thes 1:1)
Book names can be 3 letter abbreviations.
Does unlimited individual word search and exact phrase.
$string = $_GET['sstring'];
$type = $_GET['stype'];
switch ($type){
case "passage":
$book = "";
$chap = "";
$stringarray = explode(':', $string); // Split string at verse refrence/s, if exist.
$vref = $stringarray[1];
$vrefsplit = explode('-', $vref);// Split verse refrence range, if exist.
$minv = $vrefsplit[0];
$maxv = $vrefsplit[1]; // Assign min/max verses.
$bc = explode(" ", $stringarray[0]); // Split book string into array with space as delimiter.
if(is_numeric($bc[count($bc)-1])){ // If last book array element is numeric?
$chap = array_pop($bc); // Remove it from array and assign it to chapter.
$book = implode(" ", $bc); // Put remaining elemts back into string and assign to book.
}else{
$book = implode(" ", $bc); // Else book array is just book, convert back to string.
}
// Build the sql query.
$query_rs1 = "SELECT * FROM kjvbible WHERE bookname LIKE '$book%'";
if($chap != ""){
$query_rs1.= " AND chapternum='$chap'";
}
if($maxv != ""){
$query_rs1.= " AND versenum BETWEEN '$minv' AND '$maxv'";
}else if($minv != ""){
$query_rs1.= " AND versenum='$minv'";
}
break;
case "words":
$stringarray = explode(" ", $string); // Split string into array.<br />
// Build the sql query.
$query_rs1 = "SELECT * FROM kjvbible WHERE versetext REGEXP '[[:<:]]". $stringarray[0] ."[[:>:]]'";
if(count($stringarray)>1){
for($i=1;$i<count($stringarray);$i++){
$query_rs1.= " AND versetext REGEXP '[[:<:]]". $stringarray[$i] ."[[:>:]]'";
}
}
break;
case "xphrase":
// Build the sql query.
$query_rs1 = "SELECT * FROM kjvbible WHERE versetext REGEXP '[[:<:]]". $string ."[[:>:]]'";
break;
default :
break;
}
I have a loads of numbers in a string
$userlist = '12,17,46,35,32,66,43,64'; //the userlist can be as long as i want
$arr2 = explode(',', $userlist);
i dont now how to get them to output like the follow.
12,17
46,35
32,66
43,64
Thank You for taking the time to read.
You can use array_chunk to group two together again and then iterate over the groups and implode each again with the ,. Example (Demo):
$userPairings = array_chunk($arr2, 2);
foreach ($userPairings as &$pair)
{
$pair = implode(',', $pair);
}
unset($pair);
echo implode("\n\n", $userPairings);
Output:
12,17
46,35
32,66
43,64