Nov 22, 2009

What's Wrong With This Preg_replace Code?

free web hosting
Open Discussion & Free Web Hosting > Computers & Tech > Programming > Scripting > PHP

What's Wrong With This Preg_replace Code?

Houdini
I have written a JavaScript that prompts auser for 5 table attributes for entry into the posting area and it produces this:


[table bd = 15 bgc = green bdc = red cp =10 cs =10]

It is then passed through this preg_replace for display in the preview or as a submission in a post:

CODE
$txt = preg_replace( "#\[table bd=(.+?)bgc=(.+?)bdc=(.+?)cp=(.+?)cs=(.+?)\](.+?)\[/table\]#is", "<table border=\\1bgcolor=\\2bordercolor=\\3cellpadding=\\4cellspacing=\\5>\\6</table>", $txt );


What it produces however is this:

CODE
<table border = 5 bgc = blue bordercolor = black cp = 9 cs = 2>


When what I want is this:

CODE
<table border = 5 bgcolor = blue bordercolor = black cellpaddingp = 9 cellspacing = 2>


What is it that is wrong with this code and giving this odd unwanted result? Help would be most certainly appreciated because I am tired of looking at it, my eyes are getting crossed and things are getting blurry.

 

 

 


Comment/Reply (w/o sign-up)

vujsa
I'm not real good with regular expressions so I can't really answer your problem directly.

I usually use two arrays to work my preg_replace magic like I learned in this topic:
http://www.astahost.com/php-regular-expessions-t4316.html

Here is a more recent and simpler example:

I placed certain keywords in strings in my database which are to be replaced by other database entries dependant upon the user.
CODE

// Keyword replacement array here.

$search_string = array ('@&race@si',
'@&rank_suffix@si',
'@&rank@si',
'@&size@si',
'@&username@si',
'@&personal@si',
'@&timestamp@si'
);

$replace_string = array ($race,
$rank_suffix,
$rank,
$size,
$username,
$personal,
$time
);

$output = preg_replace($search_string, $replace_string, $sig_text_item_row[$x]['text_value']);


This is about the easiest example I could even think of which just happens to be the one I did today.

Anyway, if the following is true:
CODE

$race = "human";
$rank = 10;
$rank_suffix = "th";
$size = 12000;
$username = "vujsa";
$personal = "My personal message!";
$time = mktime();

AND
CODE

$sig_text_item_row[$x]['text_value']) = "My name is &usernameand I am currently ranked &rank&rank_suffix with an army of &size &race soldiers.  <br>&personal<br> Page generated at UTC: &timestamp."
echo $output;


Would return this:
QUOTE(vujsa)
My name is vujsa and I am currently ranked 10th with an army of 12000 human soldiers.
My personal message!
Page generated at UTC: 1131343747



So for your particular example, here is what I would do.
CODE

// Keyword replacement array here.

$search_string = array ('@\[@si',
'@bdc@si',
'@bd@si',
'@bgc@si',
'@cp@si',
'@cs@si',
'@\]@si'
);

$replace_string = array ("<",
"bordercolor",
"border",
"bgcolor",
"cellpadding",
"cellspacing",
">"
);

$output = preg_replace($search_string, $replace_string, $txt);


Note: I had to change the order of the array items so that "bdc" would not be returned as "borderc" instead of "bordercolor" because "bd" was found first. Also, I had to escape the brackets.

I think that if you used the same method for your replacements, it would be easier to accomplish your goal and easier to spot any bugs that you may have. Also, because this replaces what you know you will have instead of ignoring what you don't know you will have, it requires you to anticipate fewer posibilities in the end. Additionally, the array can be enlarged to allow for other replace requests as well. I like one size fits all functions and routines. Harder to set up I know but easier to request later.

I hope this helps some. cool.gif

vujsa

 

 

 


Comment/Reply (w/o sign-up)

mastercomputers
I'm positive you could grab these values without using a regular expression, but without seeing the javascript side of things, here's what I would do, in this many steps as well, I hate writing out patterns and replacements all at once.

CODE

<?php
$txt = '[table bd = 15 bgc = green bdc = red cp =10 cs =10]';
$pattern = '#\[table bd = (.+) bgc = (.+) bdc = (.+) cp =(.+) cs =(.+)]#';
$replacement = '<table border="\\1" bgcolor="\\2" bordercolor="\\3" cellpadding="\\4" cellspacing="\\5"><tr><td>\\0</td></tr></table>';
$txt = preg_replace($pattern, $replacement, $txt);
echo $txt;
?>


ok, so I'm assuming the output from the javascript is being stored in the variable txt as is. I noticed a problem with your script where you left out white spacing, also '\\6' I replaced with '\\0' as I could not see anywhere with your script that you generated this, so I only used what I had available so I hope you can fix those problems. Considering this is HTML I thought it'd be better to use quotes around values too as well as add in <tr><td></td></tr> for completeness.

Some of these HTML tags I am not fond of due to them being proprietary to the browsers, but most popular browsers have hacked together fixes to work with these tags, yet it's best to keep with standards for consistency.

I hope you'd understand the above, basically I made sure that we take white spacing for granted as well as case sensitivity. I hope in your javascript you make sure that only the correct values can be entered, no special characters unless required and none of the above mentioned keywords. Work on that side of things so as to not allow malicious input.

With the PHP side, I rather see an array of colour name values that could be used and checked against that, there's only 16 allowed web named values of colour, so it's not too much to ask for, then the rest could just be left up to hex values or rgb values in which you can perform checks on those too. Maybe with numeric values, set up a min/max value allow, no input should be converted to 0 (zero) or colour white depending on what it is for.

Cheers,


MC

Comment/Reply (w/o sign-up)


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : What39s Preg Replace Code

  1. Activation Code - (7)
  2. Php Random Selector - whats the code (2)
    Is there a PHP script that randomly selects a string from a list? example, the list is: 1-Pie
    2-Balls 3-eggs The script would view a random
    word from those 3 every time i run it. Also is there a function that gives a random number between
    0 and a number i select?...
  3. Dynamic Php Image And Better Php Code Question - (10)
    Im working on a dynamic image, can i put 2 images in same dynamic image, and can i make this code
    shorter? if ( $goal == 31 ) { $xp2 = ('14833'); } elseif ( $goal == 32 ) { $xp2 =
    ('16456'); } elseif ( $goal == 33 ) { $xp2 = ('18247'); } elseif ( $goal == 34 ) {
    $xp2 = ('20224'); } elseif ( $goal == 35 ) { $xp2 = ('22406'); } elseif ( $goal ==
    36 ) { $xp2 = ('24815'); } elseif ( $goal == 37 ) { $xp2 = ('27473'); } elseif (
    $goal == 38 ) { $xp2 = ('30408'); } elseif ( $goal == 39 ) { $xp2 = ('33648')...
  4. What's Wrong With My Php Webpage? - there may be something wrong in my php code. (2)
    This is the first time I use the functions fopen() and preg_replace() . It seems that there's
    somthing wrong. Where did I write by mistake? CODE include('data/workinfo/0.php');
    $viewwork = substr($work ,0,249); /* HERE CAN'T WORK WELL! */ $newthread =
    fopen("http://c8s2007.freetzi.com/bbs/new.php?action=article&digest=0&postdate=0&author=1&fname=0&hi
    ts=0&replies=1&pre=6&num=10&length=35&order=1", "rb"); if(!$newthread){         $newthread =
    "无法调用信息!";     }else{         $ad = "
    ";      ...
  5. How Can I Write PHP Code By This Formmail Html - (5)
    purpose is i want the information in the web page sent into my email. i just know that i need to use
    php script to operate this action ,but i have no idea about this php code. so anyone can help me
    please... thank you very much. ชื่อ
    ....................... ....... นามสกุล
    ....... ชื่อเล่น
    วันเกิด 1 2 3 4 5 6 7 8 9 10 11
    12 13 14 15 16 ...
  6. Code Snippets Repository - (0)
    Well as everybody know in these forums people posts a lot of code snippets that could be organized
    in a simple page or whatever, my question is if someone is interested to do it or if exists
    something like that here at astahost. I think it would be very helpful for everybody as well to
    keep things more organized. Best regards,...
  7. [PHP + MySQL] Separating The Results By Pages - Simple code (0)
    Hi! I will post here a code for separating the results of MySQL in pages. You ask: Why separete? I
    answer: Imagin that you have 1523 results to display. I dont have to say anything. =P Here is it.
    ------------------------------------------------------------------- CODE $conect =
    mysql_connect("host","user","password"); $select_db = mysql_select_db("database"); $query = "SELECT
    * FROM mytable"; $results = "15"; //Number of results displayed per page. if (!$page) {
        $counter = "1"; } else {     $pcounter = $page; } $start = $counter - 1; $start = $counter *
    $resu...
  8. Any Tool/software For Php Code Generation ? - Tool for code generator (3)
    Where find any tool to generate PHP class?...
  9. Php Reading And Writing To File - the code is very esay (4)
    this code to Read from file you can use this code in to make a small data base and it is very to
    use CODE $fp = fopen ("file.txt", "r"); $bytes = 4; $buffer = fread($fp, $bytes); fclose
    ($fp); print $buffer; ------------------- to write to same file CODE $fp = fopen
    ("file.txt", "w+"); fwrite ($fp, "Test"); fclose ($fp); ---------------- thanks and iwait the
    commant...
  10. How To Use Cookie In Your Web Site ? - this semple code to use and get cookie (1)
    what is the cookie ? the cookis it is some info sent and save in user computer whare i can use the
    cookies? becouse the cookies it like the header you can not send it after any output wes sent so
    you must send the cookies before any output like as ,echo and any other code i well make an E.X.
    to use the cookies you must have 2 file index.php update.php ---------- in the index.php add this
    code CODE    // This section must go at the top of the page that will display    // the
    users favorites.  These are the 'default' URLs that the user    // will se...
  11. Page Doesn't Load When This Php Code Is Present ? - (6)
    CODE switch($_GET ) {   case "home";      include("index.php");   break;   case
    "gallery";      include("gallery.php");   break;     case "links";      include("links.php");
      break;   case "guestbook";      include("../guestbook/");   break;   case "portfolio";  
       include("portfoilio.php");   break;   case "other";      include("other.php");   break;
      case "about";      include("about.php");   break;   case "contact";    
     include("contact.php");   break;   case "login";      include("/private/");   break;  
    default:...



Looking for whats, wrong, preg, replace, code

See Also,

*SIMILAR VIDEOS*
Searching Video's for whats, wrong, preg, replace, code
advertisement



What's Wrong With This Preg_replace Code?

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com