Unexpected result with preg_replace() - php

$subject = "'foo' = 'bar'";
$pattern = "/('foo' = ').*(')/";
$var = "123baz";
$replacement = "$1$var$2";
print_r(preg_replace($pattern, $replacement, $subject));
Result is 23baz' instead of 'foo' = '123baz'. Why and how can I fix this?

Think you're looking for something like this:
$subject = "'foo' = 'bar'";
$pattern = "/(= ').*(')/";
$var = "123baz";
$replacement = "= '$var'";
print_r(preg_replace($pattern, $replacement, $subject));
Output:
'foo' = '123baz'

Related

How to echo explode array?

EDIT: More clear: I want to echo $data as an array.
I have this:
$lic = $_GET['lic'];
$locationtodb = '../../files/';
$licenses = $locationtodb.'filea.txt';
$SearchLicense = $lic;
$pattern = preg_quote($SearchLicense, '/');
$pattern = "/^.*$pattern.*\$/m";
preg_match_all($pattern, $licenses, $matches);
$wholeLine = implode("\n", $matches[0]);
$data = explode(":", $wholeLine);
I can use somethings like this to replace strings:
$CurrentLine = $lic.':'.'active'.':'.$data[2];
$NewLine = $lic.':'.'suspended'.':'.$data[2];
$new_contents = file_get_contents($licenses);
$new_contents = str_replace($CurrentLine,$NewLine,$new_contents);
file_put_contents($licenses,$new_contents);
And it does work !
But if I typed something like:
echo $data[2];
It give nothing ...
Why?
Thanks.
Solution discovered!
$licenses = $locationtodb.'filea.txt';
Must be:
$licenses = file_get_contents($locationtodb.'filea.txt');

php search on string comma separated and get element that match

I have a question, if anyone can help me to solve this. I have a string separated by commas, and I want to find an item that partially matches:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
I need to get only the full string from partial match as a result of filter:
$result = "GenomaPrintOrder";
With preg_match_all you can do like this.
Php Code
<?php
$subject = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView, NewPrintOrder";
$pattern = '/\b([^,]*PrintOrder[^,]*)\b/';
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "Matched: " . $val[1]. "\n";
}
?>
Output
Matched: GenomaPrintOrder
Matched: NewPrintOrder
Ideone Demo
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$result = array();
$tmp = explode(",", $string);
foreach($tmp as $entrie){
if(strpos($entrie, $string) !== false)
$result[] = trim($entrie);
}
This will get you an array with all strings that match your search-string.
You can use regular expression to get the result:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$regex = '/([^,]*' . preg_quote($search, '/') . '[^,]*)/';
preg_match($regex, $string, $match);
$result = trim($match[1]); // $result == 'GenomaPrintOrder'
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$array = explode(" ", $string);
echo array_filter($array, function($var) use ($search) { return preg_match("/\b$searchword\b/i", $var); });
Since there are so many different answers already, here is another:
$result = preg_grep("/$search/", explode(", ", $string));
print_r($result);

preg_replace return an empty string without error

So there's my problem :
$var = "93 Avenue d'Aubière";
I used this $var with this function:
function stripAccents($str) {
$str = preg_replace('/[\x{00C0}\x{00C1}\x{00C2}\x{00C3}\x{00C4}\x{00C5}]/u','A', $str);
$str = preg_replace('/[\x{0105}\x{0104}\x{00E0}\x{00E1}\x{00E2}\x{00E3}\x{00E4}\x{00E5}]/u','a', $str);
$str = preg_replace('/[\x{00C7}\x{0106}\x{0108}\x{010A}\x{010C}]/u','C', $str);
$str = preg_replace('/[\x{00E7}\x{0107}\x{0109}\x{010B}\x{010D}}]/u','c', $str);
$str = preg_replace('/[\x{010E}\x{0110}]/u','D', $str);
$str = preg_replace('/[\x{010F}\x{0111}]/u','d', $str);
$str = preg_replace('/[\x{00C8}\x{00C9}\x{00CA}\x{00CB}\x{0112}\x{0114}\x{0116}\x{0118}\x{011A}]/u','E', $str);
$str = preg_replace('/[\x{00E8}\x{00E9}\x{00EA}\x{00EB}\x{0113}\x{0115}\x{0117}\x{0119}\x{011B}]/u','e', $str);
$str = preg_replace('/[\x{00CC}\x{00CD}\x{00CE}\x{00CF}\x{0128}\x{012A}\x{012C}\x{012E}\x{0130}]/u','I', $str);
$str = preg_replace('/[\x{00EC}\x{00ED}\x{00EE}\x{00EF}\x{0129}\x{012B}\x{012D}\x{012F}\x{0131}]/u','i', $str);
$str = preg_replace('/[\x{0142}\x{0141}\x{013E}\x{013A}]/u','l', $str);
$str = preg_replace('/[\x{00F1}\x{0148}]/u','n', $str);
$str = preg_replace('/[\x{00D2}\x{00D3}\x{00D4}\x{00D5}\x{00D6}\x{00D8}]/u','O', $str);
$str = preg_replace('/[\x{00F2}\x{00F3}\x{00F4}\x{00F5}\x{00F6}\x{00F8}]/u','o', $str);
$str = preg_replace('/[\x{0159}\x{0155}]/u','r', $str);
$str = preg_replace('/[\x{015B}\x{015A}\x{0161}]/u','s', $str);
$str = preg_replace('/[\x{00DF}]/u','ss', $str);
$str = preg_replace('/[\x{0165}]/u','t', $str);
$str = preg_replace('/[\x{00D9}\x{00DA}\x{00DB}\x{00DC}\x{016E}\x{0170}\x{0172}]/u','U', $str);
$str = preg_replace('/[\x{00F9}\x{00FA}\x{00FB}\x{00FC}\x{016F}\x{0171}\x{0173}]/u','u', $str);
$str = preg_replace('/[\x{00FD}\x{00FF}]/u','y', $str);
$str = preg_replace('/[\x{017C}\x{017A}\x{017B}\x{0179}\x{017E}]/u','z', $str);
$str = preg_replace('/[\x{00C6}]/u','AE', $str);
$str = preg_replace('/[\x{00E6}]/u','ae', $str);
$str = preg_replace('/[\x{0152}]/u','OE', $str);
$str = preg_replace('/[\x{0153}]/u','oe', $str);
$str = preg_replace('/[\x{0022}\x{0025}\x{0026}\x{0027}\x{00A1}\x{00A2}\x{00A3}\x{00A4}\x{00A5}\x{00A6}\x{00A7}\x{00A8}\x{00AA}\x{00AB}\x{00AC}\x{00AD}\x{00AE}\x{00AF}\x{00B0}\x{00B1}\x{00B2}\x{00B3}\x{00B4}\x{00B5}\x{00B6}\x{00B7}\x{00B8}\x{00BA}\x{00BB}\x{00BC}\x{00BD}\x{00BE}\x{00BF}]/u',' ', $str);
return $str;
}
This return an empty string if I use $var but it return the correct string if I use "93 Avenue d'Aubière" as a parameter.
I tried to use preg_last_error to check if there was any error but it return 0 that means no error.
I'm connectin my DB like this:
$db = new PDO('mysql:host=localhost;dbname=somedb;charset=utf8', 'username', 'password');
Getting data like this :
$sqlSelectCommandeExapaq = "SELECT * FROM commande_exapaq WHERE statut = 'en cours'";
$res = $db->query($sqlSelectCommande);
$arrayResCmd = $res->fetchAll();
Then I passed $arrayResCmd into this function :
public static function generateInterfaceFile($orders_array)
{
// Init file
$record = new DPDStation();
// Loop through each order
foreach ($orders_array as $order_data)
{
// Add data to file
$record->add($order_data['customer_adress'], 0, 35);
}
return $record;
}
And there is the DPDStation Constructor :
function __construct() {
$this->line = str_pad("", 1634);
$this->contenu_fichier = '';
}
And the add function :
function add($txt, $position, $length) {
$txt = $this->stripAccents($txt);
$this->line = substr_replace($this->line, str_pad($txt, $length), $position, $length);
}
And adding content into the file with :
$dpd = new DPDStation();
$record = $dpd->generateInterfaceFile($arrayResCmd);
file_put_contents($filename, '$VERSION=110'."\r\n", FILE_APPEND);
file_put_contents($filename, $record->contenu_fichier."\r\n", FILE_APPEND);
Because nothing was add to the file, I look into the stripAccents and the problem seems to come from it.
Thanks for your help :)

preg_replace gives back empty string

//Chars to be replaced
$suchmuster = array();
$suchmuster[0] = 'á';
$suchmuster[1] = 'à';
$suchmuster[2] = 'â';
$suchmuster[3] = 'é';
$suchmuster[4] = 'è';
$suchmuster[5] = 'ê';
$suchmuster[6] = 'í';
$suchmuster[7] = 'ì';
$suchmuster[8] = 'î';
$suchmuster[9] = 'ó';
$suchmuster[10] = 'ò';
$suchmuster[11] = '/ô/';
$suchmuster[12] = 'ú';
$suchmuster[13] = 'ù';
$suchmuster[14] = 'û';
$suchmuster[15] = ' ';
$suchmuster[16] = '.';
$suchmuster[17] = ',';
$suchmuster[18] = '-';
$suchmuster[19] = '_';
//Replaces
$ersetzungen = array();
$ersetzungen[0] = 'a';
$ersetzungen[1] = 'a';
$ersetzungen[2] = 'a';
$ersetzungen[3] = 'e';
$ersetzungen[4] = 'e';
$ersetzungen[5] = 'e';
$ersetzungen[6] = 'i';
$ersetzungen[7] = 'i';
$ersetzungen[8] = 'i';
$ersetzungen[9] = 'o';
$ersetzungen[10] = 'o';
$ersetzungen[11] = 'o';
$ersetzungen[12] = 'u';
$ersetzungen[13] = 'u';
$ersetzungen[14] = 'u';
$ersetzungen[15] = '';
$ersetzungen[16] = '';
$ersetzungen[17] = '';
$ersetzungen[18] = '';
$ersetzungen[19] = '';
$newmessage = preg_replace($suchmuster, $ersetzungen, strtolower($message));
The above code was created to replace some special chars with normal ones but no matter which $nachricht (= $message) I put in, it always gives back an empty string!
Thanks for your help.
EDIT
I Changed it to:
//Chars to be replaced
$suchmuster[0] = '/ /';
$suchmuster[1] = '/./';
$suchmuster[2] = '/,/';
$suchmuster[3] = '/-/';
$suchmuster[4] = '/_/';
//Replaces
$ersetzungen[0] = '';
$ersetzungen[1] = '';
$ersetzungen[2] = '';
$ersetzungen[3] = '';
$ersetzungen[4] = '';
$newmessage = iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', strtolower($message));
$newmessage = preg_replace($suchmuster, $ersetzungen, $newmessage);
It still gives back an empty string.
Instead of using several patterns, you can also combine the pattern to:
$nachrichtneu = preg_replace('/[,.\s_-]/', '', $nachrichtneu);
And strtolower will not convert Á and the like to á. First do the iconv conversion, then the strtolower.
Regarding your updated question:
Regular expressions use special control characters. In your case it is /./ which causes your result to be empty. . means "any character" in regex, so you are replacing each and every character with nothing.
use preg_quote() to escape special characters in regular expressions. Example: $xy = '/' . preg_quote('.') . '/';
But you can do this much simpler without using regular expressions, like:
$replaces = array(
'.' => '',
',' => '',
// ...
);
$message = str_replace(array_keys($replaces), array_values($replaces), $message);
change your code through
$suchmuster = array();
$suchmuster[0] = "/á/";
$suchmuster[1] = "/à/";
...

Replace empty spaces with ### from Text between " " in a string in PHP

I have a string like this one text more text "empty space".
How can I replace the space in "empty space" and only this space with ###?
$string = 'text more text "empty space"';
$search = 'empty space';
str_replace($search, 'empty###space', $string);
How about this, with no regular expressions:
$text = 'foo bar "baz quux"';
$parts = explode('"', $text);
$inQuote = false;
foreach ($parts as &$part) {
if ($inQuote) { $part = str_replace(' ', '###', $part); }
$inQuote = !$inQuote;
}
$parsed = implode('"', $parts);
echo $parsed;
$somevar = "empty space";
$pattern = "/\s/";
$replacement = "###";
$somevar2 = preg_replace($pattern, $replacement, $somevar);
echo $somevar2;
$string = "My String is great";
$replace = " ";
$replace_with = "###";
$new_string = str_replace($replace, $replace_with, $string);
This should do it for you. http://www.php.net/manual/en/function.str-replace.php
Edited after you comments
Maybe it's not the best solution, but you can do it like this:
$string = 'text more text "empty space"';
preg_match('/(.*)(".*?")$/', $string, $matches);
$finaltext = $matches[1] . str_replace(' ', '###', $matches[2]);

Categories