Here is the problem : I want to split a string to have the name and the first name, but my two variable are empty and i don't understant why... Can someone help me ? This my code :
$nom_aut1 = "";
$prenom_aut2 = "";
//$auteur1 is already initialized
for ($i = 0; $i < strlen($auteur1); ++$i)
{
if ($auteur1[$i] != ' ') continue;
for ($j = 0; $j < $i; ++$j)
{
$nom_aut1 .= $auteur[$j];
}
for ($j = $i+1; $j < strlen($auteur1); ++$j)
{
$nom_aut1 .= $auteur1[$j];
}
break;
}
echo '"'.$nom_aut1.'.'.$prenom_aut1.'"';
Thank you :)
Do you want to split a name into first and last name based on a space? Why not just do this:
$names = explode(" ",$name);
If $name = "Hello World"
$names will be an array such that
$names[0] = "Hello"
$names[1] = "World"
This way, if there is a middle name, you can get that as well.
You can do it this way:
$names = explode(" ",$name);
if (count($names) == 1) //only first name
{
$first = $names[0];
$last = "";
}
else if (count($names) == 2) //only first and last name
{
$first = $names[0];
$last = $names[1];
}
else //one or more middle names were provided
{
$first = $names[0];
$last = $names[count($names)-1];
for($i=1;$i<count($names)-1;$i++)
$middle .= $names[$i] . ' ';
$middle = trim($middle);
}
So, if $name = "Hello Foo Bar World"
$first = "Hello"
$last = "World"
$middle = "Foo Bar"
If the letter is not equal to ' ' it continue the loop and does not execute the 2 for loops.
But you are looking for the explode function in PHP:
<?php
$names = explode(' ', $name);
$prenom = $names[0];
$nom = $names[1];
?>
First of all, double check all your variable names.
You are saying:
$nom_aut1 = "";
$prenom_aut2 = "";
You are not using $prenom_aut2 anywhere in your code and then you are echoing:
echo '"'.$nom_aut1.'.'.$prenom_aut1.'"';
In answer to your specific question, you are declaring, populating and echoing different variables.
Another way to explode and manipulate this way!.
list($first_name, $last_name) = explode(" ", $name);
echo $first_name;
echo $last_name;
Related
My string is : Hi my, name is abc
I would like to output "Hi Name".
[Basically first word of comma separated sentences].
However sometimes my sentence can also be Hi my, "name is, abc"
[If the sentence itself has a comma then the sentence is enclosed with ""].
My output in this case should also be "Hi Name".
So Far I've done this
$str = "hi my,name is abc";
$result = explode(',',$str); //parsing with , as delimiter
foreach ($result as $results) {
$x = explode(' ',$results); // parsing with " " as delimiter
forach($x as $y){}
}
You can use explode to achieve YOUR RESULT and for IGINORE ' OR " use trim
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$first = explode(' ',$result[0]);
$first = $first[0];
$second = explode(' ',$result[1]);
$second = trim($second[0],"'\"");
$op = $first." ".$second;
echo ucwords($op);
EDIT or if you want it for all , separated values use foreach
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$op = "";
foreach($result as $value)
{
$tmp = explode(' ',$value);
$op .= trim($tmp[0],"'\"")." ";
}
$op = rtrim($op);
echo ucwords($op);
Basically it's hard to resolve this issue using explode, str_pos, etc. In this case you should use state machine approach.
<?php
function getFirstWords($str)
{
$state = '';
$parts = [];
$buf = '';
for ($i = 0; $i < strlen($str); $i++) {
$char = $str[$i];
if ($char == '"') {
$state = $state == '' ? '"' : '';
continue;
}
if ($state == '' && $char == ',') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
$buf = '';
continue;
}
$buf .= $char;
}
if ($buf != '') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
}
return implode(' ', $parts);
}
foreach (['Hi my, "name is, abc"', 'Hi my, name is abc'] as $str) {
echo getFirstWords($str), PHP_EOL;
}
It will output Hi Name twice
Demo
My code cycles through a CSV file, converting it to XML:
<?php
for ($i = 1; $i < $arraySize; $i++) {
$n = 0;
if (substr($csv[$i][0], 0, 1) == $let) {
$surName = $dom->createElement('name');
$name = $csv[$i][0];
$nameText = $dom->createTextNode($name);
$surName->appendChild($nameText);
$text = str_replace(chr(94), ",", $csv[$i][4]);
$n = $i + 1;
$next = $csv[$n][0];
while ($next == 'NULL') {
$repl = str_replace(chr(94), ",", $csv[$n][4]);
$text = $repl;
$n++;
$next = $csv[$n][0];
}
$bio = $dom->createElement('bio');
$bioText = $dom->createTextNode($text);
$bio->appendChild($bioText);
$person = $dom->createElement('person');
$person->appendChild($surName);
$person->appendChild($bio);
$people->appendChild($person);
}
}
$xmlString = $dom->saveXML();
echo $xmlString;
?>
The problem is the $text = $repl; Typing $text .= $repl; brings:
error on line 1 at column 1: Document is empty.
but omitting the . just gives the last line of text.
the backup code works:
public function test($let){
$csv = $this->readCSV("data\AlphaIndex1M.csv");
$arraySize=sizeof($csv);
$let = strtoupper($let);
//echo '';
for($i=1; $i
echo $csv[$i][0];// .'
echo ', -->'.$csv[$i][4];
$n = $i+1;
$next = $csv[$n][0];
//if($next == 'NULL'){ }
while($next == 'NULL'){
echo $csv[$n][4]. " ";
$n++;
$next=$csv[$n][0];
}
//echo ''
echo '';
}
}
//echo ''
}
You have to initialize your $text before you can append stuff!
So write this before you use it:
$test = "";
(before the while loop or even before the for loop if you want all to be appended)
$variable = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
I need to display above the $variable like
Test Company Insurance LLC Chennai Limited W-8TYU.pdf
For that I've done:
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'w-8tyu' || $test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}
}
I've got stuck in the to-do part.
I will change the specific words to uppercase using strtoupper.
Later, how should I need to merge the array?
Any help will be thankful...
$str_in = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
$lst_in = explode("_", $str_in);
$lst_out = array();
foreach ($lst_in as $val) {
switch($val) {
case "llc" : $lst_out[] = strtoupper($val);
break;
case "w-8tyu.pdf" : $lst_temp = explode('.', $val);
$lst_out[] = strtoupper($lst_temp[0]) . "." . $lst_temp[1];
break;
default : $lst_out[] = ucfirst($val);
}
}
$str_out = implode(' ', $lst_out);
echo $str_out;
Not terribly elegant, but perhaps slightly more flexible.
$v = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$acronyms = array('llc', 'w-8tyu');
$ignores = array('pdf');
$v = preg_replace_callback('/(?:[^\._\s]+)/', function ($match) use ($acronyms, $ignores) {
if (in_array($match[0], $ignores)) {
return $match[0];
}
return in_array($match[0], $acronyms) ? strtoupper($match[0]) : ucfirst($match[0]);
}, $v);
echo $v;
The ignores can be removed provided you separate the extension from the initial value.
See the code below. I have printed the output of the code as your expected one. So Run it and reply me...
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}elseif($test[$x] == 'w-8tyu.pdf'){
$file=basename($test[$x],'pdf');
$info = new SplFileInfo($test[$x]);
$test[$x] = strtoupper($file).$info->getExtension();
}
else{
$test[$x]=ucfirst($test[$x]);
}
}
echo '<pre>';
print_r($test);
echo '</pre>';
echo $output = implode(" ", $test);
I am trying to remove a list of words, which I have contained in a .txt, from a file. To do this I am reading both files using file_get_contents into strings and using str_replace.
$names = file_get_contents("countries.txt");
$map = file_get_contents("C:\\xampp\\htdocs\\www\\jvectormap\\map\\worldmap.js");
$array = explode("\n", $names);
foreach($array as $val){
$split = explode(" ", $val);
$max = count($split);
$country = "";
for($x = 1; $x < $max; $x++){
$country = $country . $split[$x];
if($x < ($max-1)){
$country = $country . " ";
}
}
$map = str_replace($country, "", $map);
}
echo $map;
The "countries.txt" contains the countries in this format:
AD Andorra
BE Belize
etc.
..which is why I am using explode() to strip the country tag.
When I echo $map the string contains all the countries even thought str_replace hasn't thrown an error. I have tried printing out $country to confirm it's reading the countries correctly along with reading it into an array and then looping through the array, using str_replace.
I think you need some modification in code
change below line
$array = explode("\n", $names);
to with these
$names = nl2br($names);
$array = explode("<br />", $names);
As you are working on window which uses \r\n for new line.
Cannot reproduce.
<?php
/* Instead of loading countries.txt */
$names = "AD Andorra
BE Belize";
$array = explode("\n", $names);
/* Instead of loading map */
$map = "Andorra Belize";
$array = explode("\n", $names);
foreach($array as $val){
$split = explode(" ", $val);
$max = count($split);
$country = "";
for($x = 1; $x < $max; $x++){
$country = $country . $split[$x];
if($x < ($max-1)){
$country = $country . " ";
}
}
$map = str_replace($country, "", $map);
}
var_dump($map);
Output:
string(1) " "
The space is expected, if you want to get rid of it use trim(). However, the replacement is working fine, if it still doesn't work your text files might be the problem.
I have a function:
function getDecision($num_players, $decisionType, $stage){
echo "in the function 1: ".$num_players."<br/>";
echo "in the function 2: ".$decisionType."<br/>";
echo "in the function 3: ".$stage."<br/>";
$x = mysql_query("
SELECT `decisionValue` FROM `teamdecision` WHERE `decisionType` = '$decisionType' && `period`= '$stage'
")or die($x."<br/><br/>".mysql_error());
$y = array();
$i="0";
while ($i<($num_players) && $row = mysql_fetch_assoc($x))
{
$y[$i] = $row['decisionValue'];
$i++;
}
return ($y);
}
Y will be populated with a number of values depending on the $num_players. I am calling the function as follows:
$value = array();
$name = array();
for ($j=0;$j<$num_players;$j++){
for ($i=0;$i<4;$i++){
$name[0] = "SUconsultant";
$name[1] = "marketT";
$name[2] = "sector";
$name[3] = "saleprice";
echo $name[$i]."<br/>";
$value[$i] = getDecision($num_players, $name[$i], $currentStage)."<br/>";
echo "Value = ".$value[$j][$i]."<br/>";
}
}
As you can see I am doing this wrong. I need to output the data located in $value however I am confused with how multi dimensional arrays work. I understand I need to read up on the subject, if possible can you point me to a suitable learning source?
So I changed up the code so that the following is being used to produce an output below:
$value = array();
$name = array();
for ($j=0;$j<$num_players;$j++){
for ($i=0;$i<4;$i++){
$name[0] = "SUconsultant";
$name[1] = "marketT";
$name[2] = "sector";
$name[3] = "saleprice";
echo $name[$i]."<br/>";
$value[$i] = getDecision($num_players, $name[$i], $currentStage)."<br/>";
echo "Value = ".$value[$j][$i]."<br/>";
}
}
I expected to output as follows:
$value[0] should contain $y which then contains each SUconsultant value. $value[1] should contain $y which then contains each marketT value and so on.
for ($i=0;$j<4;$i++){
should be
for ($j=0;$j<4;$j++){
And
$value[$i] = getDecision($num_players, $name[$i], $currentStage)."<br/>";
should be
$value[$j] = getDecision($num_players, $name[$j], $currentStage)."<br/>";
You have a $j in your first for loop, but setting and incrimenting $i in it. Maybe change them to $j as well.
EDIT
It actually looks like you have an issue with where you are returning the data:
echo "Value = ".$value[$j][$i]."<br/>";
This should be (it appears):
for ($f = 0; $f < $num_players; $f++){
echo "Value = ".$value[$i][$f]."<br/>";
}
Since you are currently on $value[$i] by the time you reach this point, then you need it to echo out one for each player.
This solution worked, after a lot of playing around it seems that the [] after of
the value array was also needed? At least I think so
$value = array();
$name = array();
for ($j=0;$j<$num_players;$j++){
for ($i=0;$i<4;$i++){
$name[0] = "SUconsultant";
$name[1] = "marketT";
$name[2] = "sector";
$name[3] = "saleprice";
echo $name[$i]."<br/>";
$value[] = getDecision($num_players, $name[$i], $currentStage);
//echo "Value = ".$value[$i]."<br/>";
echo "<br/><hr/>";
echo "Value = ".$value[$i][$j]."<br/><hr/>";
}
}
Output:
And now I have changed to:
$value[] = getDecision($num_players, $name[$i], $currentStage);
echo "Team ".$j." ".$name[$i]." = ".$value[$i][$j]."<br/>";
To get my eventual goal of: