In PHP, how to achieve the same purpose like StringTokenizer in Java? - php

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));

Related

Split out a string and search'em in sql

I'd like to split a string into array and search every split array in query that'll pull related answer from database.
Here is my code. But it's not working....
$str=$_POST['search'];
$a=preg_split("/[\s]/", $str,);
foreach ($a as $search) {
$sql = "SELECT answer FROM query_tbl WHERE (q1 like \"$search%\" OR q2 LIKE
\"$search%\" OR q3 LIKE \"$search%\" OR q4 LIKE \"$search%\")";
$record = mysqli_query($link, $sql);
$rows=mysqli_fetch_assoc($record);
echo json_encode(array('ans'=>$rows['answer']));
}
Imagine 1$str=" this makes no sense ";1 then the query will be searched by "this", "makes", "no", "sense". If the sub-string matched with answer lies in query then it'll be printed.
There are a couple of issues here. (I am assuming this is PHP)
First, I would use this syntax for your string concatenation:
"SELECT answer FROM query_tbl WHERE (q1 like '".$search."%'.OR..."
Secondly, check out the implode function fro the "OR"s and use the loop to just add the dynamic part to the static string http://php.net/manual/en/function.implode.php :
$str=$_POST['search'];
$a=preg_split("/[\s]/", $str);
var_dump($a);
foreach($a as $key => $word) {
$a[$key] = "q1 like '".$word."%'";
}
$ORS = implode(" OR ", $a);
$sql = "SELECT answer FROM query_tbl WHERE ".$ORS.";";
$record = mysqli_query($link, $sql);
$rows=mysqli_fetch_assoc($record);
echo json_encode(array('ans'=>$rows['answer']));
}

Compare two strings and generate a new string with components from both

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!

coding to check the data with array Intersect

I wanted to check to enter data into the database.Checks are as follows
$implode1 = "cat, dog, chicken";
$implode2 = "cow, goat, cat";
If the cat in the variable $implode1 is also contained in the variable $implode2, it should display a warning message. How to code for the above problem?
Help me please :(
You could explode your strings to arrays, then use array_intersect to return the values which are present in both, eg:
$string1 = 'cat, dog, chicken';
$string2 = 'cow, goat, cat';
$compare = explode(', ', $string1);
$against = explode(', ', $string2);
$matches = array_intersect($compare, $against);
$implode1 = "cat, dog, chicken";
$implode2 = "cow, goat, cat";
$imp1 = explode(', ',$implode1);
$imp2 = explode(', ',$implode2);
foreach($imp1 as $val){
if(in_array($val,$imp2)) {
echo "$val is present in $implode2";
}
}
loop the first array and check if any element is present in the second - something like this:
foreach($implode1 as $val){
if(in_array($val,$implode2)) {
echo "$val is exists in the implode2 array";
}
}
ohh, sorry, those are just strings. First explode them:
arr_implode1 = explode(", ",$implode1)
arr_implode1 = explode(", ",$implode2)
You could just check before inserting the values into a database if they already exist:
if not exists (select * from TestTable where column NOT IN {$implode})
begin
...Do something here!!
end
Create yourself a function that is able to extract the values out of each string in form of an array, then get the intersection. If it is not FALSE, there is an intersection, so do the warning:
$values = function($string) {
return explode(', ', $string);
};
if (array_intersect($values($implode1), $values($implode2))) {
trigger_error('Values intersect', E_USER_WARNING);
}
See it in action.

MYSQL insert comma separated values into separate fields?

I know its a strange question, but I have one input field that does a live search for locations. The final value is displayed like this:
State,Suburb,Post Code
NSW,Sydney,2210
What I need to do now is split the three values into single values and update them into my separate fields for one row.
I don't want to update multiple rows but just one.
e.g.:
fields ( state | suburb | postcode )
values ( NSW | sydney | 2210 )
What php commands would I use to split those commas off and create single $values for each item?
Use explode on the string.
$values = 'A,B,C,D';
$values = explode(',', $values);
Each item can then be accessed from an array indexed from 0.
$val = "NSW,Sydney,2210";
$valArr = explode(",", $val);
$query = "UPDATE MyTbl SET State = '$valArr[0]', Suburb = '$valArr[1]', Post_Code = '$valArr[2]' WHERE ...";
The easiest way I think, see the manual for explode:
$result_array = explode(',', $your_variable);
list($state, $suburb, $postcode) = explode(',', $value);
Would this work?
$header = "State,Suburb,Post Code"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become State|Suburb|Post Code
to access each value separately, you can use $items[0], $items[1] ..
$data = "NSW,Sydney,2210"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become NSW|Sydney|2210

insert in database from each line of textarea field by php

How i can insert in database from textarea field that each line is a table in database
means I want insert in database from each line of textarea field by php
my information like this:
Name | FullName | Age
and database table:
id (auto insert),
name,
fullname,
age
thanks
i would suggest using a delimiter at the end of the line and then convert it into an array using explode(), here is what you could do.
//Make sure your text have (,) comma at the end of every line
$text = 'My Name,
My Full Name,
24';
//Convert it into an array
$text = explode(',', $text);
//fetch the value and assign it to variables then do an insert operation
//Use mysql_real_escape_string() to escape SQL injections.
$name = mysql_real_escape_string($text[0]);
$FullName = mysql_real_escape_string($text[1]);
$age = mysql_real_escape_string($text[2]);
and then you can create query like this.
$query = "INSERT INTO persons(name, fullName, age) values($name, $fullName, $age)";
$result = mysql_query($query);
// assuming the text area value is in $_GET["text"]
$lines = explode("\n", $_GET["text"]);
foreach($lines as $line) {
list($name, $fullName, $age) = explode(" | ", $line);
mysql_query("INSERT INTO table (name, fullname, age) VALUES ('$name', '$fullName', $age)");
}
Hope this helps:
// assuming textarea name is $_POST['data']
$_POST['data'] = 'Jane | Jane Doe | 23
zxc
sadas
John | John Doe | 48
';
// Set and trim data
$data = (array_key_exists('data', $_POST)) ? trim($_POST['data']) : '';
if ($data !== '') {
$lines = explode("\n", $data);
$sql = 'insert into table (name, fullname, age) values ';
$sql_parts = array();
foreach ($lines as $line) {
$sql_part = array(
'name' => null,
'full_name' => null,
'age' => null,
);
// If no divider found, skip this line
if (strpos($line, ' | ') === false)
{
continue;
}
list($sql_part['name'], $sql_part['full_name'], $sql_part['age']) = explode(' | ', $line);
// For the sake of this example
// i will assume all fields are required
// so let's check for that:
foreach ($sql_part as $key => $item) {
// Trim and sanitize the data:
$item = mysql_real_escape_string(trim($item));
// If any item is empty continue to the next line of data
if ($item === '') {
continue 2;
}
$sql_part[$key] = "'".$item."'";
}
$sql_parts[] = '('.implode(',', $sql_part).')';
}
if (empty($sql_parts) === false) {
$sql .= implode(',', $sql_parts);
mysql_query($sql);
}
}
Split the string, for example http://php.net/manual/en/function.explode.php

Categories