PHP - str_replace not working - php

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.

Related

how to explode following string

How do i explode a following string
$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368"
Such that output array will contain
[
"ProductId" => "123",
"Name" => "Ancient Roots, Modern Pursuits",
"Country" => "India",
"City" => "Bangalore",
"Price" => "3368"
]
I tried to explode by "comma", then each element again explode by "equal to" as.
$arr = explode(",", $str);
and again
$prodarr = explode("=", $arr[0]);
$product["ProductId"] = $prodarr[1]
But facing problem when another comma is exist in value like in name "Ancient Roots, Modern Pursuits"
Your structure is very weak for breaking. But you can still try to parse it.
First explode on =. You will have next key and current value.
Then loop these and explode on , and select last element for next key and all previous parts as value (sample):
<?php
$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368";
$chunks = explode('=', $str);
$keys = [];
$values = [];
foreach ($chunks as $i => $chunk) {
$parts = explode(',', $chunk);
if ($i != count($chunks) - 1) {
$keys[] = trim(array_pop($parts));
}
if ($i != 0) {
$values[] = implode(',', $parts);
}
}
var_dump(array_combine($keys, $values));
I played a little bit around. I used preg_match_all() to extract the Patterns which contain characters that are no , and no = followed by a = followed by characters that are no = followed by a , or end of line. here is the result:
$result = array();
preg_match_all('/([^=,]+=[^=]+)(,|$)/', $string, $matches);
foreach($matches[1] as $data){
$data = explode('=', $data);
$result[trim($data[0])] = trim($data[1]);
}
$result = json_encode($result);
The result is:
{"ProductId":"123","Name":"Ancient Roots, Modern Pursuits","Country":"India","City":"Bangalore"}
Try something like this
<?php
$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368";
$str_arr = explode(",", $str);
$json_array = array();
for ($i = 0; $i < sizeof($str_arr); $i++)
{
if (isset($str_arr[$i + 1]))
{
if (strpos($str_arr[$i + 1], '=') !== false)
{
$prod = explode("=", $str_arr[$i]);
$json_array["" . $prod[0] . ""] = "" . $prod[1] . "";
}
else
{
$textAppend = "," . $str_arr[$i + 1];
$prod = explode("=", $str_arr[$i]);
$json_array["" . $prod[0] . ""] = "" . $prod[1] . "" . $textAppend . "";
$i++;
}
}
else
{
$prod = explode("=", $str_arr[$i]);
$json_array["" . $prod[0] . ""] = "" . $prod[1] . "";
}
}
var_dump($json_array);
?>

How to splitt a string to an array with keys and values using php

I have string and I want to splitt it to array and remove a specific part and then convert it back to a string .
$string = "width,100;height,8600;block,700;narrow,1;"
I want to search block in this string and remove it with its value "block,700;" and get the string as "width,100;height,8600;narrow,1;"
below is my code php which i tried.Please advice me
$outerARR = explode(";", $string);
$arr = array();
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$arr[] = $innerarr;
}
for ($i = 0; $i < count($arr); $i++) {
if (in_array($arr, 'block')) {
unset($arr[$i]);
}
}
Please note that "block" in aboive string will not always contain and the value may differ. So I can't use string replace . please advice
You essentially want to replace part of your string:
$string = "width,100;height,8600;block,700;narrow,1;";
$regex = '#(block,(.*?);)#';
$result = preg_replace($regex, '', $string);
echo $result;
Try this:
$string = "width,100;height,8600;block,700;narrow,1;"
$outerARR = explode(";", $string);
$arr = array();
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$arr[$innerarr[0]] = $innerarr[1];
}
if (array_key_exists('block', $arr)) {
unset($arr['block']);
}

Remove all paragraphs based on order (after the 2rd, 3th or 4th...)

I got this
$description = '<p>text1</p><p>text2</p><p>text3</p><p>text4</p><p>textn</p>'
I want to remove only what comes after <p>text3</p>
My result would be:
$description = '<p>text1</p><p>text2</p><p>text3</p>'
My guess is that we need to use preg_replace with some regex but I can't manage to write a working one.
You could...
function str_occurance($needle, $haystack, $occurance) {
$occurance += 2;
$arr = explode($needle, $haystack, $occurance);
unset($arr[0]);
$arr = array_values($arr);
$key = count($arr) - 1;
unset($arr[$key]);
$str = $needle . implode($needle, $arr);
return $str;
}
Not the prettiest, but it works.
Edit: To use:
$description = '<p>text1</p><p>text2</p><p>text3</p><p>text4</p><p>textn</p>';
$split = '<p>';
$return = 3;
$new = str_occurance($needle, $description, $return);
echo $new; // returns <p>text1</p><p>text2</p><p>text3</p>

How can i explode the string with , and |

How can i explode this? mars#email.com,123,12,1|art#hur.com,321,32,2
the output should be :
$email = mars#email.com
$score = 123
$street = 12
$rank = 1
then remove the |
$email = art#hur.com
$score = 321
$street = 32
$rank = 2
$string = mars#email.com,123,12,1|art#hur.com,321,32,2
explode( ',', $string );
is that correct?
foreach(explode('|', $str) as $v){
$data = explode(',',$v);
echo '$email = '.$data[0].
'$score = '.$data[1].
'$street = '.$data[2].
'$rank = '.$data[3];
}
You might want to use strtok() rather than explode().
http://www.php.net/manual/en/function.strtok.php
$arr = preg_split( '"[,|]"', 'mars#email.com,123,12,1|art#hur.com,321,32,2' );
$len = count($arr);
for( $i = 0; $i < $len; $i+=4 ) {
$email = $arr[$i];
$score = $arr[$i+1];
$street = $arr[$i+2];
$rank = $arr[$i+3];
}
you need to store the new array in variable >
$arr = explode(',',$string);
and I dont get what you want to do with the second part (after the |), but you can get the first par by doing this > $half = explode('|',$string)[0];
You need to unravel it in the right order:
first the blocks separated by |
then individual cells separated by ,
A concise way to do so is:
$array = array_map("str_getcsv", explode("|", $data));
Will give you a 2D array.
Use strtok and explode.
$tok = strtok($string, "|");
while ($tok !== false) {
list($email, $score, $street, $rank) = explode(',', $tok);
$tok = strtok(",");
}
I think what you want is something like this
$output = array();
foreach (explode('|', $string) as $person) {
$output[] = array(
'email' => $person[0],
'score' => $person[1],
'street' => $person[2],
'rank' => $person[3]
)
}
This stores all the results in a multidimensional array. For example, to print person 1's email, you'd use
echo $output[0]['email']; // mars#email.com
and to access person 2's street, you'd use
echo $output[1]['street']; // 32

PHP - string parsing & concatenation problems

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;

Categories