Swapping two variables with RegEx - php

So here is my code, and then I will explain what I am having trouble with:
foreach($people as $person){
// counter for each person
$counter = 0;
// get variables for each item
list($fullName,$phoneNumber,$address,$birthday,$salary) = explode(':', $person);
// get variables for first and last name
list($firstName, $lastName) = explode(" ", $fullName);
// get variables for phone numbers
list($areaCode, $middleDigits, $lastDigits) = explode('-',$phoneNumber);
//get variables for address
list($street,$city,$statezip) = explode(", ", $address);
// get variables for state and zip separately
list($state,$zipCode) = explode(" ", $statezip);
// print file with the first and last names reversed
$tempFName = $firstName;
$tempLName = $lastName;
echo $newPerson = (preg_replace("/($tempLName)($tempFName)/", $firstName, $lastName, $person))."<br/>";
$counter++;
}
What I want to do, is print the original $person, but with the $firstName and $lastName 's reversed. I'm able to replace the values and then print out each variable, but then it wouldn't have the same format as $person originally did unless I formatted each line. I was wondering if there was a way to do it without formatting each output to look identical to the original $person variable.
Thanks!

It looks as if Firstname and Lastname are always separated by whitespace and preceed the first colon character... if this is correct the above may be overkill. Try this:
echo $newPerson = (preg_replace("/(.*?)\s+(.*?)\:/", '$2,$1:', $person))."<br/>";

Related

Explode/Implode in foreach loop

I have a list of strings like
$list = "foo, bar";
I use explode on this list to get the list items as an array:
$strings = explode(", ", $list);
Now I need to take each item of the array and pass it to an API one by one and the API will return the IDs for the list entries. I want to end up with a string that is just like $list but with the IDs instead of the strings.
My problem is that I can't pass an array to the API funtion. I need to do it for every single list item. So I'm looping through the array:
foreach($strings as $names){
$ID = $o_api->GetGroupIdsByName($s_token, $names)->getData();
$AssignedGroups = implode("", $ID).";";
echo $AssignedGroups;
}
If I run this code the result is: 3;4;
Which is exactly what I need to pass it to another API function. But when I need to re-use this list outside of the loop . If I then use $AssignedGroups I only get the last ID, not the 2 (or more) merged ones.
What am I doing wrong?
Here is the complete code for reference:
$Groups = explode(", ", $value["Groups"]);
//var_dump($Groups);
foreach($Groups as $Names){
$GroupIDs = $o_api->GetGroupIdsByName($s_token, $Names)->getData();
$AssignedGroups = implode("", $GroupIDs).";";
echo $AssignedGroups;
}
$o_api->CreateUser($s_token, $Login, $Password, $IsOfflineUser, $IsWindowsUser, $FirstName, $LastName, $AssignedGroups, $Ratings);
What really should be done here:
$Groups = explode(", ", $value["Groups"]);
//var_dump($Groups);
// init as empty array
$AssignedGroups = [];
foreach ($Groups as $Names) {
$GroupIDs = $o_api->GetGroupIdsByName($s_token, $Names)->getData();
// a new string to array
$AssignedGroups[] = implode(';', $GroupIDs);
}
// here you can implode again:
$AssignedGroups = implode(';', $AssignedGroups);
// or even with another delimiter
$AssignedGroups = implode(',', $AssignedGroups);
Fiddle with implode example.

Removing beginning and end character from String without altering array

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.

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!

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

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

PHP: Separate one field in two

As many recommend me to separate firstname and lastname instead of "full_name" with everything in, how can I separate them to each variables, so if for you example type in the field: "Dude Jackson" then "Dude" gets in $firstname and Jackson in the $lastname.
It's impossible to do with 100% accuracy, since the first/last name contains more information than a single "full name". (A full name can include middle names, initials, titles and more, in many different orders.)
If you just need a quick fix for a legacy database, it might be OK to split by the first space.
Assuming first name always comes first and there's no middle name:
list($firstname, $lastname) = explode(' ', $full_name);
This simply explodes $full_name into an array containing two strings if they're separated by only one space, and maps them to the first and last name variables respectively.
You can do:
list($first_name,$last_name) = explode(' ',$full_name);
This assumes that you full name contains first name and last name separated by single space.
EDIT:
In case the lastname is not present, the above method give a warning of undefined offset. To overcome this you can use the alternative method of:
if(preg_match('/^(\S*)\s*(\S*)$/',$full_name,$m)) {
$first_name = $m[1];
$last_name = $m[2];
}
$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$lastname = $a[1];
you would need to explode the value into its parts using a space as the separator
http://php.net/manual/en/function.explode.php
I am no PHP programmer, but for a quick fix, without data loss,
$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$count = 1;
$lastname = "";
do {
$lastname .= $a[$count]." ";
$count++;
} while($count<count($a));
$lastname = trim($lastname);
This should save all remaining part of name in $lastname, should be helpful for names like "Roelof van der Merwe". Also you can throw in checks for $full_name as first name only, without last name.
This is the code/solution
$full_name = "Dude Jackson";
$a = explode($full_name, " ",1);
if(count($a) == 2)
{
$firstname = $a[0];
$lastname = $a[1];
}
if(count($a) < 2)
{
$firstname = $full_name;
$lastname = " ";
}

Categories