views:

153

answers:

4

Hi. I have a string

&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&

and i have to delete, say, this part &185601651932|mobile|3|120|1& (starting with amp and ending with amp) knowing only the first number up to vertical line (185601651932)

so that in result i would have

&168491968426|mobile|3|100|1&114192088691|mobile|3|555|5&

How could i do that with PHP preg_replace function. The number of line (|) separated values would be always the same, but still, id like to have a flexible pattern, not depending on the number of lines in between the & sign.

Thanks.

P.S. Also, I would be greatful for a link to a good simply written resource relating regular expressions in php. There are plenty of them in google :) but maybe you happen to have a really great link

A: 
preg_replace("/&185601651932\\|[^&]+&/", ...)

Generalized,

$i = 185601651932;
preg_replace("/&$i\\|[^&]+&/", ...);
KennyTM
dr3w
A: 

if you want real flexibility, use preg_replace_callback. http://php.net/manual/en/function.preg-replace-callback.php

stillstanding
A: 

Important: don't forget to escape your number using preg_quote():

$string = '&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
$number = 185601651932;
if (preg_match('/&' . preg_quote($number, '/') . '.*?&/', $string, $matches)) {
    // $matches[0] contains the captured string
}
soulmerge
A: 

It seems to me you ought to be using another data structure than a string to manipulate this data. I'd want this data in a structure like

Array(
  [id] => Array(
     [field_1] => value_1
     [field_2] => value_2
  )
)

Your massive string can be massaged into such a structure by doing something like this:

$data_str = '168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
$remove_num = '185601651932';

/* Enter a descriptive name for each of the numbers here 
- these will be field names in the data structure */
$field_names = array( 
    'number',
    'phone_type',
    'some_num1',
    'some_num2',
    'some_num3'
);

/* split the string into its parts, and place them into the $data array */
$data = array();
$tmp = explode('&', trim($data_str, '&'));
foreach($tmp as $record) {
    $fields = explode('|', trim($record, '|'));
    $data[$fields[0]] = array_combine($field_names, $fields);
}

echo "<h2>Data structure:</h2><pre>"; print_r($data); echo "</pre>\n";
/* Now to remove our number */
unset($data[$remove_num]);
echo "<h2>Data after removal:</h2><pre>"; print_r($data); echo "</pre>\n";
gnud