I already know how to use string replace by creating an array manually:
array('value1','value2','value3','value4');
But how do I use str_replace by values from a Database?
$original_string = (fruit_1+fruit_2+fruit_3);
table1 database values: fruit_1 fruit_2 fruit_3
table2 database values: 237 9388 2377
output what i want: (237+9388+2377)
The normal str_replace procedure i already know:
$replaced_string = str_replace($searchwords, $replacewords, $original_string );
How do i get all the values from the database and process them by str_replace?
Can this be done by creating an array or so?
I use PDO to get values from the database.
Thank you!!!
Martijn
str_replace can take array arguments as well, so you can do this:
$original_string = '(fruit_1+fruit_2+fruit_3)';
$find = explode(' ', 'fruit_1 fruit_2 fruit_3');
$replace = explode(' ', '237 9388 2377');
$new_string = str_replace($find, $replace, $original_string);
// gives (237+9388+2377)
Related
This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 1 year ago.
I have values like
"34,37"
and I want to create array using this values, array like
array('34','37')
How to create such array if I have values.
hope this will help you :
you can use explode function if you have values as string;
$string = '34,37';
$data = explode(',',$string):
print_r($data); /*output array*/
for more : http://php.net/manual/en/function.explode.php
If you have a string like this:
$str = "1,2,3,4,5,6";
And you want to convert it into array, just use explode()
$myArray = explode(',', $str);
var_dump($myArray);
Have a look here for more information
As per my comment, you should use preg_split function. for more details about preg_split function please read PHP manual and also you can use explode function Explode function PHP manual
<?php
$string = '34,37';
$keywords = preg_split("/[\s,]+/", $string);
//OR $keywords = preg_split("/,/", $string); separated by comma only
print_r($keywords);
you can check your desired Output here
Try this,
$val = "34,37"
$val = explode(',', $val);
print_r($val);
output of above array:
Array
(
[0] => 34,
[1] => 37
)
$d5 = preg_grep("/(#[0-9]{1,11})/", $d);
in the code above:
$d is a $_POST method textarea input.
I have a preg_grep to find and capture numbers following an # symbol like this: #1234567890
I want to INSERT the $d5 results to a table in the database, but since the preg_grep should return an array I can't put them in as it is. So I tried to use the following method
$d5string = implode(", ", $d5);
but obviously I couldn't address the $d5 results appropriately.
How can I convert this $d5 results to string so I can INSERT the results to a row under related column?
EDIT/UPDATE:
I wrote the below function and realized that I was giving a string to the preg_grep which takes an array. So my question was not logical. I'd like to update my question: How to capture and put regex results to database?
function activeMention($string) {
$find = '/#([0-9]{1,11})/';
return preg_grep($find, $string);
}
I replaced preg_grep() with preg_match_all() in the function. Now the error is gone and var_dump shows int(0)
on variable $d5 = activeMention($string); I put a $_POST['textarea_name'] value as $string
NOW:
The function looks like this:
function activeMention($string) {
$find = '/#([0-9]{1,11})/';
return preg_match_all($find, $string, $matches);
implode(', ', $matches);
}
When I try to insert the variable below to the database I get only the count of captured strings:
$d5 = activeMention($_POST['textarea_name']);
What I actually needed was the array values in 1 string like "#123123, #1234567, #12345"
To get more than one match from a regular expression, you could use preg_match_all like this:
// Define string
$d = 'Here goes one #1234567890 and a #987654321';
// Run regular expression and put matches into $d5 (array with arrays)
$found = preg_match_all("/(#[0-9]{1,11})/", $d, $d5);
// Iterate result
foreach ($d5[0] as $number) {
echo $number, PHP_EOL; // ... or insert into database
}
Output:
#1234567890
#987654321
Here's finally how I did it:
I got rid of the function and used preg_match_all like this:
preg_match_all('/#([0-9]{1,11})/', $_POST['textarea_name'], $out);
$d5s = implode(', ', $out[0]);
and added $d5s to the VALUES in the query to insert into database.
I have this string that contains the following quote-contained, comma-separated values:
"field","anotherfield","yetanotherfield"
I need to populate an array with the content of these fields, without the quotes.
What I'm currently doing is:
$string = str_replace('"', NULL, $string);
and then
$array = explode(',', $string);
It works, but it breaks when there's a comma inside any field. How can I prevent this?
first, trim " from the start and end of string.
$string = trim('"field","anotherfield","yetanotherfield","other, another"', '"');
and after explode "," between values you need.
$array = explode('","', $string);
To parse entire CSV file into an array you could use str_getcsv function:
$array = array_map( 'str_getcsv', file( 'path-to-file/file.csv' ) );
I have a string stored in a variable, this string may appear in the next ways:
$sec_ugs_exp = ''; //Empty one
$sec_ugs_exp = '190'; //Containing the number I want to delete (190)
$sec_ugs_exp = '16'; //Containing only a number, not the one Im looking for
$sec_ugs_exp = '12,159,190'; // Containing my number at the end (or in beginning too)
$sec_ugs_exp = '15,190,145,86'; // Containing my number somewhere in the middle
I need to delete the 190 number if it exists and deleting also the comma attached after it unless my number is at the end or it is alone(there is no commas in that case)
So in the examples I wrote before, I need to get a return like this:
$sec_ugs_exp = '';
$sec_ugs_exp = '';
$sec_ugs_exp = '16';
$sec_ugs_exp = '12,159';
$sec_ugs_exp = '15,145,86';
Hope I explained myself, sorry about my English. I tried using preg_replace and some other ways, but I always failed in detecting the comma.
My final attempt not using regex:
$codes = array_flip(explode(",", $sec_ugs_exp));
unset($codes[190]);
$sec_ugs_exp = implode(',', array_keys($codes));
A simple regex should do the trick: /(190,?)/:
$newString = preg_replace('/(190,?)/', '', $string);
Demo: http://codepad.viper-7.com/TIW9D6
Or if you want to prevent matches like:
$sec_ugs_exp = '15,1901,86';
^^^
You could use:
(190(,|$))
Quick and dirty, but should work for you:
str_replace(array(",190","190,","190"), "", $sec_ugs_exp);
Note the order in the array is important.
$array = explode ( ',' , $sec_ugs_exp );
foreach ( $array AS $key => $number )
{
if ( $number == 190 )
{
unset($array[$key]);
}
}
$sec_ugs_exp = implode ( ',' , $array );
This will work if a number if 1903 or 9190
None of the answers here account for numbers beginning or ending with 190.
$newString = trim(str_replace(',,', ',', preg_replace('/\b190\b/', '', $string)), ',');
try
str_replace('190,', '', $sec_ugs_exp);
str_replace('190', '', $sec_ugs_exp);
or
str_replace('190', '', $sec_ugs_exp);
str_replace(',,' ',', $sec_ugs_exp);
if there are no extra spaces in your string
what is the best way of extracting multiple (~40 values) from a text file using php?
the data is more or less like:
NAMEA valuea
NAMEB valueb
I'm looking for a proper* approach to extracting this data into a data-structure, because i will need to specify regexs for all of them (all 40).
did i make myself clear?
*meaning, the default/painful method would be for me to do:
$namea = extractfunction("regexa", $textfilevalue);
$nameb = extractfunction("regeb", $textfilevalue);
... 40 times!
The lines may not be in the same order, or be present in each file. Every NAMEA is text like: "Registration Number:", or "Applicant Name:" (ie, with spaces in what i was calling as NAMEA)
Response to the Col.
i'm looking for a sensible "way" of writing my code, so its readable, modifiable, builds an object/array thats easily callable, etc... "good coding style!" :)
#Adam - They do actually... and contain slashes as well...
#Alix - Freaking marvelous man! THat was GOOD! would you also happen to have any insights on how I can "truncate" the rsultant array by removing everything from "key_x" and beyond? Should i open that as a new question?
Here is my take at it:
somefile.txt:
NAMEA valuea
NAMEB valueb
PHP Code:
$file = file_get_contents('./somefile.txt');
$string = preg_replace('~^(.+?)\s+(.+?)$~m', '$1=$2', $file);
$string = str_replace(array("\r\n", "\r", "\n"), '&', $string);
$result = array();
parse_str($string, $result);
echo '<pre>';
print_r($result);
echo '</pre>';
Output:
Array
(
[NAMEA] => valuea
[NAMEB] => valueb
)
You may also be able to further simplify this by using str_getcsv() on PHP 5.3+.
EDIT: My previous version fails for keys that have spaces like #Col. Shrapnel noticed. I didn't read the question with enough attention. A possible solution since you seem to be using keys that always have : appended is this:
$string = preg_replace('~^(.+?):\s+(.+?)$~m', '$1=$2', $file);
To remove everything from key_x to the end of the file you can do something like this:
$string = substr($string, 0, strpos($string, 'key_x'));
So the whole thing would look like this:
somefile.txt:
Registration Number: valuea
Applicant Name: valueb
PHP Code:
$file = file_get_contents('./somefile.txt');
$string = substr($file, 0, strpos($file, 'key_x'));
$string = preg_replace('~^(.+?):\s+(.+?)$~m', '$1=$2', $string);
$string = str_replace(array("\r\n", "\r", "\n"), '&', $string);
$result = array();
parse_str($string, $result);
echo '<pre>';
print_r($result);
echo '</pre>';
Output:
Array
(
[Registration_Number] => valuea
[Applicant_Name] => valueb
)
as far as I get it you can use file() to get an array of strings and then parse these strings with some regexp.
if you add a = sign between names and values, you'll be ble to get the whole thing at once using parse_ini_file()
Assuming your keys (namea, nameb) never have spaces in them:
$contents = file('some_file.txt'); // read file as array
$data = array();
foreach($contents as $line) { // iterate over file
preg_match('/^([^\s]+)\s+(.*)/', $line, $matches); // pull out key and value into $matches
$key = $matches[1];
$value = $matches[2];
$data[$key] = $value; // store key/value pairs in $data array
}
var_dump($data); // what did we get?