Catch a word into quotes using preg_replace - php

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!

Related

Split a string at comma character but ignore if said character is nested inside parentheses

I'm currently working as a php dev, and now has an assignment with some old php legacy code that's intended to filter certain car details before adding it into the DB.
What I'm currently stuck on is how I'm supposed to skip splitting the models inside of the parenthesis
Example:
"v70, 790, v50 (v40, v44), v22"
Expected output:
[ "v70", "790", "v50 (v40, v44)", "v22" ]
So that the , inside of the parentheses is disregarded by the split.
Any help and pointers is greatly appreciated!
You can use preg_split() method for this (documentation). You can use this to split the string based on a regex pattern for comma separated values but ignored if these are between parentheses.
This code works for your example:
<?php
$string = 'v70, 790, v50 (v40, v44), v22';
$pattern = '/,(?![^(]*\)) /';
$splitString = preg_split($pattern, $string);
Output of $splitString looks like:
array (size=4)
0 => string 'v70' (length=3)
1 => string '790' (length=3)
2 => string 'v50 (v40, v44)' (length=14)
3 => string 'v22' (length=3)

Removing whitespace string from a string variable in 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;

preg_split url slug and id

I currently have this URL pattern:
foo-bar-1
bar-foo-bar-2
etc
I'd like to get the words separated from the number but I'm having some trouble completely understanding how to do that.
I started with this which got me close:
$slug = 'foo-bar-1';
preg_split('/(\d+)$/', $slug);
array (size=2)
0 => string 'foo-bar-' (length=8)
1 => string '' (length=0)
But I can't seem to finish it up. I'd like it to be this:
array (size=2)
0 => string 'foo-bar' (length=7)
1 => string '1' (length=1)
Any help is greatly appreciated! Thank you!
Try this:
preg_split('/-(?=\d+$)/', $slug);
I use - as separator and I check if it is followed by a number at the end of the string with a lookahead (?=...)

How to split an array by every nth appearance of a string?

This question is different to Split, a string, at every nth position, with PHP, in that I want to split a string like the following:
foo|foo|foo|foo|foo|foo
Into this (every 2nd |):
array (3) {
0 => 'foo|foo',
1 => 'foo|foo',
2 => 'foo|foo'
}
So, basically, I want a function similar to explode() (I really doubt that what I'm asking will be built-in), but which 'explodes' at every nth appearance of a certain string.
How is this possible?
You can use explode + array_chunk + array_map + implode
$string = "foo|foo|foo|foo|foo|foo";
$array = stringSplit($string,"|",2);
var_dump($array);
Output
array
0 => string 'foo|foo' (length=7)
1 => string 'foo|foo' (length=7)
2 => string 'foo|foo' (length=7)
Function used
function stringSplit($string, $search, $chunck) {
return array_map(function($var)use($search){return implode($search, $var); },array_chunk(explode($search, $string),$chunck));
}

Remove first two words from a string

I have a string:
$string = "R 124 This is my message";
At times, the string may change, such as:
$string = "R 1345255 This is another message";
Using PHP, what's the best way to remove the first two "words" (e.g., the initial "R" and then the subsequent numbers)?
Thanks for the help!
$string = explode (' ', $string, 3);
$string = $string[2];
Must be much faster than regexes.
One way would be to explode the string in "words", using explode or preg_split (depending on the complexity of the words separators : are they always one space ? )
For instance :
$string = "R 124 This is my message";
$words = explode(' ', $string);
var_dump($words);
You'd get an array like this one :
array
0 => string 'R' (length=1)
1 => string '124' (length=3)
2 => string 'This' (length=4)
3 => string 'is' (length=2)
4 => string 'my' (length=2)
5 => string 'message' (length=7)
Then, with array_slice, you keep only the words you want (not the first two ones) :
$to_keep = array_slice($words, 2);
var_dump($to_keep);
Which gives :
array
0 => string 'This' (length=4)
1 => string 'is' (length=2)
2 => string 'my' (length=2)
3 => string 'message' (length=7)
And, finally, you put the pieces together :
$final_string = implode(' ', $to_keep);
var_dump($final_string);
Which gives...
string 'This is my message' (length=18)
And, if necessary, it allows you to do couple of manipulations on the words before joining them back together :-)
Actually, this is the reason why you might choose that solution, which is a bit longer that using only explode and/or preg_split ^^
try
$result = preg_replace('/^R \\d+ /', '', $string, 1);
or (if you want your spaces to be written in a more visible style)
$result = preg_replace('/^R\\x20\\d+\\x20/', '', $string, 1);
$string = preg_replace("/^\\w+\\s\\d+\\s(.*)/", '$1', $string);
$string = preg_replace('/^R\s+\d+\s*/', '', $string);

Categories