473,394 Members | 2,002 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

RegEx with preg_replace

Hello,

I have a string like this:

var1: value1...valueI var2: value1...valueJ ... varN:
value1...valueK

this is an example:

breakfast: coffee eggs lunch: sandwich apple dinner: chicken wine
cake

I'm trying to use preg_replace to change "lunch:" values to a code
number, in order to get in the example:

breakfast: coffee eggs lunch: 0503 dinner: chicken wine cake

keeping the rest of variables and values unchanged.

Take in account, that I'm only sure that I have the "lunch:" word
delimitation (and its values), I don't know if exists "breakfast:" or
"dinner:"; but I'm sure that if the variable exists, then the values
exists too.

Thanks,

Sebastian.
Jul 17 '05 #1
3 3455
Sebastian Araya wrote:
this is an example:

breakfast: coffee eggs lunch: sandwich apple dinner: chicken wine
cake

I'm trying to use preg_replace to change "lunch:" values to a code
number, in order to get in the example:

breakfast: coffee eggs lunch: 0503 dinner: chicken wine cake

keeping the rest of variables and values unchanged.


Not sure if preg_* is the way to go ... but, what the hell :-)

<?php
$foods['00'] = 'coffee';
$foods['01'] = 'wine';
$foods['02'] = 'cake';
$foods['03'] = 'apple';
$foods['04'] = 'eggs';
$foods['05'] = 'sandwich';
$foods['06'] = 'chicken';
$line = 'breakfast: coffee eggs lunch: sandwich apple dinner: chicken wine cake';

preg_match('/^(breakfast: .* )?lunch: (.*)( dinner:.*)?$/U', $line, $meal);
$liunch = explode(' ', $meal[2]);

echo $meal[1], 'lunch: ';
foreach ($lunch as $foodname) echo array_search($foodname, $foods);
echo $meal[3], "\n";
?>
Output of this script is:
breakfast: coffee eggs lunch: 0503 dinner: chicken wine cake
--
--= my mail box only accepts =--
--= Content-Type: text/plain =--
--= Size below 10001 bytes =--
Jul 17 '05 #2
Use preg_replace_callback(). In the callback function, parse the list of
lunch items and look up the corresponding code for each.
In the regexp you need to use preg's lookbehind feature, to look for the
string "lunch:" but keeping it out of the match. The following snippet
should yield the right result:

$s = "breakfast: coffee eggs lunch: sandwich apple dinner: chicken wine
cake";

$food_ids = array( 'coffee' => '00', 'wine' => '01', 'cake' => '02',
'apple' => '03', 'eggs' => '04', 'sandwich' => '05', 'chicken' => '06' );

function food_to_code($matches) {
global $food_ids;
$foods = preg_split('/\\s+/', $matches[0]);
$codes = "";
foreach($foods as $food) {
$code = $food_ids[$food];
if($code) {
$codes .= $code;
}
}
return "$codes ";
}

echo preg_replace_callback('/(?<=lunch:\\s)(?:\\w+(?:\\s|$))+/',
'food_to_code', $s);

Uzytkownik "Sebastian Araya" <ar*****@numisys.com.ar> napisal w wiadomosci
news:67*************************@posting.google.co m...
Hello,

I have a string like this:

var1: value1...valueI var2: value1...valueJ ... varN:
value1...valueK

this is an example:

breakfast: coffee eggs lunch: sandwich apple dinner: chicken wine
cake

I'm trying to use preg_replace to change "lunch:" values to a code
number, in order to get in the example:

breakfast: coffee eggs lunch: 0503 dinner: chicken wine cake

keeping the rest of variables and values unchanged.

Take in account, that I'm only sure that I have the "lunch:" word
delimitation (and its values), I don't know if exists "breakfast:" or
"dinner:"; but I'm sure that if the variable exists, then the values
exists too.

Thanks,

Sebastian.

Jul 17 '05 #3
A more efficient and compact code to achieve the same with minor
modifications to ignore multiple space characters in string:

[SNIP]

$s = "breakfast: coffee eggs lunch: sandwich apple dinner:
chicken wine
cake";

$food_ids = array( 'coffee' => '00', 'wine' => '01', 'cake' =>
'02',
'apple' => '03', 'eggs' => '04', 'sandwich' => '05', 'chicken' =>
'06' );

function food_to_code($matches)
{
return preg_replace('/\w+/e','$GLOBALS[\'food_ids\'][\'$0\']',
trim($matches[0]));
}

echo preg_replace_callback('/(?<=lunch:\s)(?:[\w\s]+)(?=\s\w+:\s|$)/',
'food_to_code',$s);

[/SNIP]

A little more compact code (i guess more *efficient* also &
complicated too):
[/SNIP]

$s = "breakfast: coffee eggs lunch: sandwich apple dinner:
chicken wine
cake";

$food_ids = array( 'coffee' => '00', 'wine' => '01', 'cake' =>
'02',
'apple' => '03', 'eggs' => '04', 'sandwich' => '05', 'chicken'
=> '06' );

$pattern = '/(?<=lunch:\s)(?:[\w\s]+)(?=\s\w+:\s|$)/e';
$replacement = 'preg_replace(\'/\\w+/e\',\'$food_ids[\\\'\$0\\\']\'
,trim(\'$0\'))';

echo preg_replace($pattern, $replacement,$s);

[/SNIP]

--

Wish you all Happy new year!!

Cheers!
Rahul
"Chung Leong" <ch***********@hotmail.com> wrote in message news:<cc********************@comcast.com>...
Use preg_replace_callback(). In the callback function, parse the list of
lunch items and look up the corresponding code for each.
In the regexp you need to use preg's lookbehind feature, to look for the
string "lunch:" but keeping it out of the match. The following snippet
should yield the right result:

$s = "breakfast: coffee eggs lunch: sandwich apple dinner: chicken wine
cake";

$food_ids = array( 'coffee' => '00', 'wine' => '01', 'cake' => '02',
'apple' => '03', 'eggs' => '04', 'sandwich' => '05', 'chicken' => '06' );

function food_to_code($matches) {
global $food_ids;
$foods = preg_split('/\\s+/', $matches[0]);
$codes = "";
foreach($foods as $food) {
$code = $food_ids[$food];
if($code) {
$codes .= $code;
}
}
return "$codes ";
}

echo preg_replace_callback('/(?<=lunch:\\s)(?:\\w+(?:\\s|$))+/',
'food_to_code', $s);

Uzytkownik "Sebastian Araya" <ar*****@numisys.com.ar> napisal w wiadomosci
news:67*************************@posting.google.co m...
Hello,

I have a string like this:

var1: value1...valueI var2: value1...valueJ ... varN:
value1...valueK

this is an example:

breakfast: coffee eggs lunch: sandwich apple dinner: chicken wine
cake

I'm trying to use preg_replace to change "lunch:" values to a code
number, in order to get in the example:

breakfast: coffee eggs lunch: 0503 dinner: chicken wine cake

keeping the rest of variables and values unchanged.

Take in account, that I'm only sure that I have the "lunch:" word
delimitation (and its values), I don't know if exists "breakfast:" or
"dinner:"; but I'm sure that if the variable exists, then the values
exists too.

Thanks,

Sebastian.

Jul 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Alexandre Lahure | last post by:
Hi all I'd like to execute a piece of code when I find a particular string. So I used preg_replace('/my_regex/e', 'my_piece_of_code', $my_string) Actually, I'd like to convert something like...
6
by: Brian Richmond | last post by:
I'm trying to use a regular expression to match a hidden html tag and replace it with the results of a mysql query. The query is based off a part of the hidden tag. For example: The article...
3
by: Red | last post by:
In netscape bookmark files, there are lots of lines like this: <DT><A HREF="http://www.commondreams.org/" ADD_DATE="1091500674" LAST_CHARSET="ISO-8859-1" ID="rdf:#$uiYyb3">Common Dreams</A> I...
2
by: brendan | last post by:
trying to clear out all text between the outermost <---Message Start---> and <---Message End---> tags using snippet
5
by: Markus Ernst | last post by:
Hello I have a regex problem, spent about 7 hours on this now, but I don't find the answer in the manual and googling, though I think this must have been discussed before. I try to simply...
8
by: erikcw | last post by:
Hi all, I'm trying to write a regex pattern to use in preg_replace. Basically I want to put around every line (\n) in this variable. However, I need to exclude lines that already have brackets...
5
by: Petra Meier | last post by:
Hello, I use the following script to parse URI and email: function parseLinks($sData){ $regexEmail = "/\w+((-\w+)|(\.\w+))*\@+((\.|-)+)*\.+/"; $sData = preg_replace($regexEmail, "<a...
1
by: semi_evil | last post by:
I'm trying to achieve the following: start form entry user enters form data and submits ($form_data) preg_match_all data for $pattern, store matches in $match_arr if one or more matches...
5
by: nel | last post by:
I have two tags: <!--// Remove Begin //--and <!--// Remove End //--> I want to use regi_replace() to remove everything between these tags. The thing is, these tags can be repeated throughout...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.