简体   繁体   中英

How do I return words from strings using regular expressions?

I have some data which looks like:

{i:0;s:2:"69";i:1;s:2:"70";i:2;s:2:"71";i:3;s:2:"72";i:4;s:2:"73";i:5;s:2:"74";i:6;s:2:"75";i:7;s:2:"76";i:8;s:2:"77";}

I need to remove all items within quotation marks, eg 69,70,..,77 .

I understand I should use the preg_split function.

I'm looking for help regarding the regular expression I need to pass to preg_split in order to return the required data.

Edit

Sorry, my initial question wasn't clear. I want to gather all values between speech marks and have them returned in an array (i'm not interested in keeping the rest of the data - all I require are the values within speech marks)

Edit 2 The data is a serialized object, I didn't include the full object in order to save space.

without regexp:

$v = 'a:9:{i:0;s:2:"69";i:1;s:2:"70";i:2;s:2:"71";i:3;s:2:"72";i:4;s:2:"73";i:5;s:2:"74";i:6;s:2:"75";i:7;s:2:"76";i:8;s:2:"77";}';
$v = unserialize($v);
print_r($v);
$v = array_combine(array_keys($v), array_fill(0, count($v), ''));
echo serialize($v); 

but this looks, how max mentioned, like a (part of a) serialized object.
you should check if you are able to work with the complete syntax of it...

update

well, if you only want the values of this serialized array, it gets even easier:

$v = 'a:9:{i:0;s:2:"69";i:1;s:2:"70";i:2;s:2:"71";i:3;s:2:"72";i:4;s:2:"73";i:5;s:2:"74";i:6;s:2:"75";i:7;s:2:"76";i:8;s:2:"77";}';
$v = unserialize($v);
$v = array_values($v);
print_r($v);

output:

Array
(
    [0] => 69
    [1] => 70
    [2] => 71
    [3] => 72
    [4] => 73
    [5] => 74
    [6] => 75
    [7] => 76
    [8] => 77
)

array_values() isn't even necessary, really.

If you really want to delete all numbers between quotation marks, just use

$string = preg_replace('/"[0-9]+"/', '""', $string);

If you want to delete everything between these, use

$string = preg_replace('/"[^"]+"/', '""', $string);

To your edited question:

preg_match_all('/"([^"]+)"/', $string, $matches);

$matches will contain an array of arrays containing the strings.

Something like this should work:

$str = '{i:0;s:2:"69";i:1;s:2:"70";i:2;s:2:"71";i:3;s:2:"72";i:4;s:2:"73";i:5;s:2:"74";i:6;s:2:"75";i:7;s:2:"76";i:8;s:2:"77";}';
$str = preg_replace('#:"[^"]*"#', '', $str);
echo $str . "\n";

This will be more useful

$data = 'a:9:{i:0;s:2:"69";i:1;s:2:"70";i:2;s:2:"71";i:3;s:2:"72";i:4;s:2:"73";i:5;s:2:"74";i:6;s:2:"75";i:7;s:2:"76";i:8;s:2:"77";}';
$data = unserialize($data);
echo implode(',',$data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM