Removing whitespace string from a string variable in php - php

I tried removing the whitespace but don´t work. I use trim for remove spaces.
I realized in php, for callback in a responseText ajax.
$orderHTML = $producto['id'].'#'.$producto['nombre_producto'].'*'.$producto['precioVenta'].'*'.$producto['descripcion'].'*'.$producto['descatalogado'].'#'.$producto['cantidad_stock'];
echo trim($orderHTML);
In my ajax the result data is:
data: " 1#jeans*1.00**0#100"
I´ve got my call a php is:
GET "http://localhost:8080/ajax/products_ajax.php?idProducto=1&opcion=2"
My php is:
<?php
require_once '../../vendor/autoload.php';
require_once '../../config.php';
require_once '/functions/function_orders.php';
$opcion = $_REQUEST['opcion'];
switch($opcion)
{
case '1':
if(isset($_POST['parametro1'])&&isset($_POST['parametro2']))
{
$orderHTML = getOrdersProduct($_POST['parametro1'],$_POST['parametro2']);
echo trim($orderHTML);
}
break;
case '2':
if(isset($_GET['idProducto']))
{
$producto = getOrdersProduct1($_GET['idProducto']);
$orderHTML = trim($producto['id']).'#'.$producto['nombre_producto'].'*'.$producto['precioVenta'].'*'.$producto['descripcion'].'*'.$producto['descatalogado'].'#'.$producto['cantidad_stock'];
echo trim($orderHTML);
}
}
My query in idiorm:
function getOrdersProduct1($identificador)
{
return ORM::for_table('producto')->
where('id',$identificador)->find_one()->as_array();
}
I realize one var_dump($productos);die();
array (size=11)
'id' => string '1' (length=1)
'nombre_producto' => string 'jeans' (length=6)
'nombre_latin' => null
'peso' => string '100.00' (length=6)
'descatalogado' => string '0' (length=1)
'dimensiones' => null
'descripcion' => null
'cantidad_stock' => string '100' (length=3)
'precioVenta' => string '1.00' (length=4)
'gama_id' => string '2' (length=1)
'proveedor_id' => string '1' (length=1)
What am I doing wrong? thanks

you have to use the trim function with the second argument correctly. if all that fails try
$str = trim(preg_replace('/\s+/',' ', $str));
the line of code will remove extra spaces, as well as leading and trailing spaces. this is combined with trim and preg_replace.

It looks to me that your $producto['id'] is a text field of fixed length and therefore has leading spaces.
You should use trim() or ltrim() to remove these before concatenating the values into the $orderHTML, then later when you come to read the code it will be self documenting as to why you had to do this manipulation, like so
$orderHTML = ltrim($producto['id']) . '#' .
$producto['nombre_producto'].'*'.
$producto['precioVenta'].'*'.
$producto['descripcion'].'*'.
$producto['descatalogado'].'#'.
$producto['cantidad_stock'];
echo $orderHTML;

Related

how to fix preg_match() unknown modifier '?' in localeconv()

the problem s in the 'decimal_point' => string '/'
but did anyone have a good solution to fix it?
the error:
preg_match() unknown modifier '?'
the function :
* #param string $str input string
* #return boolean
*/
public static function numeric($str)
{
// Get the decimal point for the current locale
list($decimal) = array_values(localeconv());
// A lookahead is used to make sure the string contains at least one digit (before or after the decimal point)
return (bool) preg_match('/^-?+(?=.*[0-9])[09]*+'.preg_quote($decimal).'?+[0-9]*+$/D', (string) $str);
}
it's localeconv() dump :
array (size=18)
'decimal_point' => string '/' (length=1)
'thousands_sep' => string ',' (length=1)
'int_curr_symbol' => string 'IRR' (length=3)
'currency_symbol' => string 'ريال' (length=8)
'mon_decimal_point' => string '/' (length=1)
'mon_thousands_sep' => string ',' (length=1)
'positive_sign' => string '' (length=0)
'negative_sign' => string '-' (length=1)
'int_frac_digits' => int 2
'frac_digits' => int 2
'p_cs_precedes' => int 0
'p_sep_by_space' => int 0
'n_cs_precedes' => int 0
'n_sep_by_space' => int 0
'p_sign_posn' => int 3
'n_sign_posn' => int 3
'grouping' =>
array (size=1)
0 => int 3
'mon_grouping' =>
array (size=1)
0 => int 3
the relate issue on github
koseven/issues #351
Since you're using / as the delimiter in your regexp, pass it to the preg_quote function as well, as the second parameter:
return (bool) preg_match('/^-?+(?=.*[0-9])[09]*+' . preg_quote($decimal, '/') . '?+[0-9]*+$/D', (string) $str);
// -----------------------------------------------------------------------^
Quote from the manual:
Note that / is not a special regular expression character.
[...]
delimiter
If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required
by the PCRE functions. The / is the most commonly used delimiter.

Php Array sorting assoc key after intersect key

Currently I have this:
$pattern = array('industry_id','category_id','subcategory_id');
$data = array('advert_id' => string '261501' (length=6)
'advert_type_id' => string '7' (length=1)
'user_id' => string '6221' (length=4)
'industry_id' => string '17' (length=2)
'category_id' => string '769' (length=3)
'subcategory_id' => string '868' (length=3)
'model' => string 'Custom Semi Drop Deck Trailer' (length=29)
'description' => string 'Industry: Trailer );
Then:
array_intersect_key( $data , array_flip($pattern) );
Using array_interect_key & array_flip to get the values from $data based on $pattern, I will get a result like this:
array (size=3)
'category_id' => string '769' (length=3)
'subcategory_id' => string '930' (length=3)
'industry_id' => string '17' (length=2)
Unfortunately as you can see the result key sorting is not the same that I declared in $pattern. Is there a shorthand way to sort it like I declared in $pattern because after this I want to implode the array and do something like this industry_id.category_id.subcategory_id without hard coding the keys.
Since you already figured out array_intersect_key method which will not get you the desired key ordering of $pattern, try this instead:
// since original $pattern is not ASSOC (only vals)
// flip it so defined vals become keys
$pattern_flipped = array_flip($pattern);
$result = array();
foreach ($pattern_flipped as $k => $v) {
if (isset($data[$k])) {
$result[$k] = $data[$k];
}
}
var_dump($result); // test
// can use original 0 1 2 dynamic keys for concatenation
echo $result[$pattern[0]], $result[$pattern[1]], $result[$pattern[2]], '<br>';
// or use hardcoded keys
echo $result['industry_id'], $result['category_id'], $result['subcategory_id'], '<br>';
You know I'm not sure how you're getting the result you describe. I've tried your code and I get
array (size=3)
'industry_id' => string '17' (length=2)
'category_id' => string '769' (length=3)
'subcategory_id' => string '868' (length=3)
You could do this another way though using array_filter
$newData = array_filter($data, function($key) use ($pattern) {
if (in_array($key, $pattern))
return true;
}, ARRAY_FILTER_USE_KEY)

Search file for text starting and ending with..and add the inbetween in an array (PHP)

I need to parse a lot of files and get their header declaration from all of them and add them all to an array..It doesnt matter if its the same or not since i'll use array_unique after to get only the unique once.
Some files have comments on the top so i can just pick the first line. The declaration is like this:
private ["_aaaaaaa", "_bbbbbb", "_ccccc", "_dddddddd"];
but sometimes it can be like this (no space)
private["_aaaaaaa","_bbbbbb","_ccccc","_dddddddd"];
or like this (if the guy who wrote it didnt pay attention)
private["_aaaaaaa", "_bbbbbb","_ccccc", "_dddddddd"];
So far i got this:
<?php
$str = 'private ["_aaaaaaa","_bbbbbb","_ccccc","_dddddddd"];';
$arr = Array();
$start = 'private [';
$end = '];';
$pattern = sprintf(
'/%s(.+?)%s/ims',
preg_quote($start, '/'), preg_quote($end, '/')
);
if (preg_match($pattern, $str, $matches)) {
list(, $match) = $matches;
echo $match;
}
?>
which outputs :
"_aaaaaaa","_bbbbbb","_ccccc","_dddddddd"
Still though that doesnt cover it....plus how will i make that to an array...?
Is there a simple way of doing this ? I've got the function that parses all the files in a folder and subfolder...i just need first to parse all the files and make this array which i'll later use in my main function.
Any help would be appreciated.
-Thanks
This should work -
/*
Function-> get_header()
Input -> The header string.
Output -> An array of header's parameters.
*/
function get_header($string){
if(preg_match("/private\s?\[(.*?)\];/", $string, $matches)){
return preg_split("/(\s*)?,(\s*)?/",$matches[1]);
}
return Array();
}
//Assuming these to be the different file headers.
$headers = Array(
'private ["_aaaaaaa", "_bbbbbb", "_ccccc","_dddddddd"];',
'private ["_4","_3","_2","_1" ];',
'private["_a", "_b","_c", "_d"];'
);
$header_arr = Array();
foreach($headers as $h){
$header_arr = array_merge($header_arr, get_header($h));
}
var_dump($header_arr);
OUTPUT-
/*
array
0 => string '"_aaaaaaa"' (length=10)
1 => string '"_bbbbbb"' (length=9)
2 => string '"_ccccc"' (length=8)
3 => string '"_dddddddd"' (length=11)
4 => string '"_4"' (length=4)
5 => string '"_3"' (length=4)
6 => string '"_2"' (length=4)
7 => string '"_1" ' (length=5)
8 => string '"_a"' (length=4)
9 => string '"_b"' (length=4)
10 => string '"_c"' (length=4)
11 => string '"_d"' (length=4)
*/

Catch a word into quotes using preg_replace

I have a string with many caracters and I need obtain data from it.
First of all, I did explode by ';', now I have an array and of each row I have a word into quotes.
I want to remove all, less this word into quotes. I know that is more easy to obtain these words with preg_match, but how is into an array, to save up to go over the array again, I would like to clean it directly with preg_replace.
$array = explode(';', $string);
//36 => string 's:7:"trans_1"' (length=13)
//37 => string 's:3:"104"' (length=9)
//38 => string 's:5:"addup"' (length=11)
//39 => string 's:1:"0"' (length=7)
$array = preg_replace('! !i', '', $array);
I would like to obtain:
//36 => string 'trans_1' (length=6)
//37 => string '104' (length=3)
//38 => string 'addup' (length=5)
//39 => string '0' (length=1)
I tryed differents things, but I can't rid off the letters outside the quotes.
While this isn't a direct answer to your question it solves your problem. The data you are looking at came from the php function serialize() to retrieve the data from that string you need to use the php function unserialize().
$data = unserialize($string);
You could try
preg_replace('!.*"([^"]*)".*!i', '\1', $array);
\1 refers to the first captured group!

php regex/preg_match for beginner

I am not good at expressions
I would like to match the string below of a string.
http://www.site.com/ * .js
preg_match('(http://www\.site\.com/).*(\.js)',$html,$match);
I know this code is not right. * Represents any file with .js extension.
Could anyone guide me with the expression.
Sorry if any duplication.
You have to use delimiters such as '#', '#' or '/' in the pattern :
$url = 'http://www.site.com/javascript/test.js';
$preg_match = preg_match('#(http://www\.site\.com/)(.*)(\.js)#', $url, $matches);
if($preg_match === 1)
{
var_dump($matches);
// displays :
// array
// 0 => string 'http://www.site.com/javascript/test.js' (length=38)
// 1 => string 'http://www.site.com/' (length=20)
// 2 => string 'javascript/test' (length=15)
// 3 => string '.js' (length=3)
}
else
{
// doesn't match
}

Categories