Jump to content

ragax

Members
  • Posts

    186
  • Joined

  • Last visited

Everything posted by ragax

  1. I tested this code, it works. $subject='"SELECT * FROM `{settings}`"'; $s=preg_replace('/"SELECT \* FROM `\{([^}]+)\}`"/', '"SELECT * FROM `".$tables[\'\1\']"', $subject); echo $s;
  2. Hi Rifts, That's a neat little function that would solve about half of the requests for regex help on the www!!! If I was building a library of extended preg functions, I would include that.
  3. Sweet, glad to hear it. Wishing you a fun weekend.
  4. Yes, but watch out, in the code I gave you, gallery() has to return something, not just echo. I'm sure you're aware of that, though. Wishing you a fun weekend.
  5. Okay, run this. This time, both power-push2 and 33 are parameters that you feed to your regex. You can wrap the regex in a function of $myID, $myID2. Again, allowing for multiple instances of the {power-push2, 33} couple. (As shown when you run the code on this tweaked test string. Otherwise we can simplify to a preg_match rather than preg_match_all.. <?php $myID = 'power-push2'; $myID2='33'; $pattern=',<div id="'.$myID.'">(<a href="\.\./\?id='.$myID2.'".*?)</div,'; $s=' blah <div id="power-push2"><a href="../?id=11" class="imghover"><img src="../1.jpg" alt="abc" width="160" height="213" /></a><p><span class="p-w15">username</span></p></div> <div id="power-push2"><a href="../?id=22" class="imghover"><img src="../1.jpg" alt="abc" width="160" height="213" /></a><p><span class="p-w15">username</span></p></div> <div id="power-push2"><a href="../?id=33" class="imghover"><img src="../1.jpg" alt="abc" width="160" height="213" /></a><p><span class="p-w15">username</span></p></div> <div id="power-push2"><a href="../?id=33" class="anotherclass"><img src="whatever, just showing you we can capture several" /></a><p><span class="p-w15">username</span></p></div> <div id="power-push2"><a href="../?id=55" class="imghover"><img src="../1.jpg" alt="abc" width="160" height="213" /></a><p><span class="p-w15">username</span></p></div> blah'; if(preg_match_all($pattern, $s, $matches, PREG_PATTERN_ORDER)) { $sz=count($matches[1]); for ($i=0;$i<$sz;$i++) echo "Match: ".htmlentities($matches[1][$i])."<br />"; } ?> Let me know if this works for you. ps. Hi abareplace, nice to see you here! // Edited to add CODE tags. That's what happens when you press Submit without previewing.
  6. Do you mean that the ID is a variable? Then run this sample code. Your ID is stored in $myID. You can add programmatic control if you need to check multiple IDs. I assume there won't be more that one of each ID, but just in case, this returns every instance. <?php $myID = 'power-push2'; $pattern=',<div id="'.$myID.'">(.*?)</div,'; $s=' blah <div id="power-push2"><a href="../?id=12" class="imghover"><img src="../1.jpg" alt="abc" width="160" height="213" /></a><p><span class="p-w15">username</span></p></div> blah'; if(preg_match_all($pattern, $s, $matches, PREG_PATTERN_ORDER)) { $sz=count($matches[1]); for ($i=0;$i<$sz;$i++) echo "Match: ".htmlentities($matches[1][$i])."<br />"; } ?> Hope this helps.
  7. ragax

    str_replace

    Sorry, don't know.
  8. ragax

    str_replace

    This looks like a straight literal replacement, with no regex to speak of. You are using str_replace, that is not a regex function (unlike preg_replace). In that sense, it might be more a vbull question than a regex or php question. Maybe you have formatted SEARCH CODE like a regex: '/<div class="postbody">/' This would not work in str_replace because it will search for the delimiters---which aren't there. For SEARCH CODE, I would try the simple string you supplied: '<div class="postbody">' Maybe let us know what you have tried and what hasn't worked, and we can help you troubleshoot some more. Wishing you a beautiful day
  9. Hi again Ianco, I gave you a dummy function gallery() because you didn't say what you wanted it to do. You can fill it up with whatever you like. Sure, it can use a $username variable or whatever you like. Or maybe I am misunderstanding? Wishing you a fun day
  10. Hi Ian, You're welcome, thrilled that it's working for you. Wishing you a fun day.
  11. Edit: For thoroughness, I should have mentioned that for the places where you are indeed able to use the raw match (i.e., without putting it through something like strtolower or htmlentities as in Sandeep's example), a simple preg_replace will do---you won't need a callback function as there is nothing to process.
  12. Yes, trying to decipher the instructions some more, it seems he may want to replace some text either with: 1. The content of a variable named by the match, e.g. $gallery, OR with 2. The result of a function named by the match, e.g. gallery() Here are solutions to both. 1. Replacing Text with Content of Variable Named by the Match <?php $s='text, e.g. [!gallery!], that is contained in blog post'; $gallery='//variable GALLERY was here//'; $p=',\[!([^!]+)!\],'; $s=preg_replace_callback($p, function ($match) {global $gallery; return ${$match[1]};}, // $gallery $s); echo $s; ?> Note that if you use this solution, you will have to declare all the other potential variables inside the function, e.g. global $otherReplacementVariable; 2. Replacing Text with Result of Function Named by the Match <?php $s='text, e.g. [!gallery!], that is contained in blog post'; $p=',\[!([^!]+)!\],'; $s=preg_replace_callback($p, function ($match) {return $match[1]();}, // calls gallery() $s); function gallery() {return '//function GALLERY was here//';} echo $s; ?> Ianco, you must have been away from your computer for the new year... Good for you! When you have a moment, can you please indicate if this works for you? Wishing you all a happy new year.
  13. Hi Sean, I haven't followed the whole discussion, but it seems to me that you are just wanting to tweak Sandeep's code a little? For instance, in you want to write url instead of code. In your call back, you want to replace this string: with whatever precedes your url, for instance: "<a href="http://" Same for the string after the url. Last, for the middle of the string, You might want the raw text instead? .$src[1]. I don't know. You have all the elements in your hand now, you should be able to tweak Sandeep's code to your heart's content. Happy new year.
  14. Hi ianco, From your description, I am not clear about what you want to replace with what. But let's start with the first step. It sounds to me like you want to create a variable whose name depends on the content of the [!variable!]. Here is a piece of code that does that: the variable $gallery is created on the fly, based on the match. <?php $s='text, e.g. [!gallery!], that is contained in blog post'; $p=',\[!\K[^!]+,'; $hit=preg_match($p,$s,$match); if($hit) { ${$match[0]}=$match[0]; echo $gallery; } ?> Let me know if this is a step in the right direction. It may be that this is all you need in order to build your replace?
  15. Hi again Debbie, A second message because something just crossed my mind. I wonder if this could be the source of outstanding confusion, as I did not emphasize it: At the end of the first lookahead (looking for eight to twenty characters), the regex engine hasn't moved. (It is still ready to eat up characters at the very beginning of the string.) It is still planted in the same place. It has only LOOKED ahead. So the second lookahead also LOOKS from the very beginning (looking for an upper-case character). At the end of it, the engine is still planted at the beginning, ready to eat up whatever you tell it to MATCH. All the lookaheads in this expression do that. They start looking from the very beginning. The engine's position in the string doesn't change. After all the lookaheads, when the dot-star starts its job of eating up any character, it does so from the very beginning of the string, since we haven't moved at all.
  16. Hi Debbie, Great to hear from you. Sorry to hear that you haven't been feeling well. I hope you soon have a chance to give your stomach a break. I see it the same way. <rant>In my view, this is part of the short-attention-span world where people are too busy with Facebook and their cell phones to learn something for themselves. Yes, most of these resources feel like copy-paste. But not the ones I have pointed you to, I think. You can tell the difference when someone has been down in the trenches working with code.</rant> Could this be a surface impression, I wonder? Do please share one or two spots where such contradictions seem to exist, and I will do my very best to clear it up for you. It must be frustrating to navigate a sea of contradicting information, and I feel annoyed on your behalf. Okay, hanging on to my seat. Actually, it is rather important. So rather than avoiding it, I will explain it. The regex engine starts at the beginning of the string. Then it moves from left to right as it tries to build a match. Sometimes, it has to move backward (backtrack). "Eating up characters" just means that the regex engines consumes a number of characters on the string as it moves from left to right. For instance, if your string is Monday25 and your regex is \w+\d+, first the regex consumes (eats up) the M, the o,n,d,a,y (one by one!), then it eats up the 2 and the 5. This is not correct regex. It means "look for between eight and twenty times" (the {8,20}) of "any amount of anything (the dot-star), then look for the end of the string". This would be my face if I has to look for eight times any amount of anything. If you remove the star, it works as it means "look for between eight and twenty times of any character". It is a lookahead, so it does not "eat up" (consume) any characters. The regex engine stays planted at the beginning of the string. It just looks ahead if it can find what you told it to look for. Probably, but not in the above expression. Dot means "any character". Star means "any amount of (and possibly none)". Dot star means "any amount of any character, and possibly none". Footnote (please don't spend time on this paragraph until the rest of the page is clear): depending on whether we are in "dot-match mode" (activated for instance by (?s) ), the dot may or may not match the end of line character. Normally, it does not. In this expression, a dot would work just as well as a [\d\D]. If your input allowed carriage returns (which a password field would not), then the dot version would be preferable. In this case it really does not matter: there are always more than one way to write an expression. It's fun to switch it up sometimes. If you wanted to use the dot to write this lookahead, you would write: (?=.{8,20}$) Right. Right. Right. (More precisely, any character from A to Z). Nope. But that's great because we have found the source of confusion. It means look for any number of characters, THEN for an upper-case letter. See, the expression in the parentheses is a small regex in itself. It is sequential, meaning, you read it from left to right. If it said (?=abc), it would not be the same as (?=cba). The regex engine reads look for this, THEN that, THEN the other. So the secret of this lookahead is that it looks if there is an upper-case character ANYWHERE in the string. Because the lookahead goes through any number of characters, THEN an upper-case character. Note that we could have written it with a lazy quantifier instead: (?=.*?[A-Z]).* Whether one works better than the other depends on the expected position of the upper-case character. Bottom-line: both work. Correct. No, that's really up to you to decide what a special character means. Will you allow a letter in the Thai alphabet in your password? I don't think so. Will you allow all punctuation marks? Great, you can use [:punct:] I left it up to you to decide what to put in that class. Looking forward to it. Both ways may very well be right. I hope you feel better soon! It must be hard to work through this regex with a foggy head. If you can crack this one in that state, you will be able to crack anything. Wishing you a good rest. Looking forward to reading you again. I have a feeling that it's just about to click for you. If my explanation is still not clear, please keep insisting on why it "looks wrong" until I have given you an acceptable explanation.
  17. Greetings Debbie, Morning here in New Zealand, great to hear from you. There is also a lot of *incorrect* information out there Yes, that is true. Often I read advice that is a case of the blind leading the blind, though I also often see advice by extremely skilled regex practitioners. Maybe I need to go buy a book? The two books on the tutorial are excellent. I recommend starting with the tutorial in my sig, but if it starts too fast, step back and start at the beginning with Jan's tutorial on regular-expressions.info. Then come back. The books and Jan's site are excellent, they really are, and yet lacking in some ways that the tutorial in my sig tries to fill. You can answer "how do I match a phone number", or you can answer "what's a good way to use this syntax", and "why should I use this instead of that", and all kinds of questions that mean you are learning a craft rather than applying a recipe. You have to do both: learn recipes, and learn the craft. In the tut there is a section on all the bits of syntax that use (?, and since you are starting out with lookaheads you might find this worthwhile very soon. Ultimately if you get hooked by regex you will want to eat up all of these resources. To complete this survey of the landscape: the PHP manual is a good reference for PCRE regex, but short on explanations and potentially confusing. The original PCRE manual is much better. Based on that explanation, I would think the code should be... I'm going to have to insist. The code is correct (I'm sure you've tried it by now), the alternative is not. Let me try to explain what might be the source of confusion. You wrote this: [A-Z](?=.*) This means: match one upper-case character, then look ahead if you can find anything (the dot-star). The lookahead is meaningless, because you can always match dot-star. As for the [A-Z], it is not part of a lookahead, so it requires you to match an upper-case character right after whatever you have matched before, and right before whatever you're going to match next. Now let's look again at the expression I sent you. First, let's talk about its general "personality". What it does is let you stand at the beginning of the string (thanks to the caret anchor). From the beginning of the string, you look ahead five times. Always from the beginning of the string, because no matching whatsoever happens until we have finished the lookaheads. So the lookaheads are a series of tests: let's see if somewhere in the distance I can see an upper-case letter... Etc. Once the lookaheads are done, we know we have matched all the requirements of the password, so we are allowed to match anything. And we do! With the dot-star. We use a dot-star because we are absolutely confident that all are requirements have been met. At that stage, we say "okay, let's eat up this entire string". Now let's dive into one of the lookaheads (the one you were mentioning): (?=.*[A-Z]) # lookahead: an upper-case character You say that it looks flipped, and that suggests to me that the source of confusion is that you might think that part of this line contributes to the final match. But actually, everything inside the parentheses is part of the lookahead. There is no matching done whatsoever here: we don't eat up any characters, we just look. All the matching happens at the very end of the regex, with the dot-star. What does the lookahead do? The first thing to remember is that you are standing at the caret, at the beginning of the string. The lookahead starts looking from the very next character in the string. So we cannot just say: (?=[A-Z]) because this would mean: look to see if the very first character in the string is an upper-case letter. Instead, we say "look if we can eat up any number of characters, THEN find an upper-case letter". This allows the upper-case letter to be first, last, or anywhere in the string. In lookahead parlance, this looks like this: (?=.*[A-Z]) # lookahead: an upper-case character So the key is to understand that the lookahead starts looking from the very point where you are standing. If you want it to look way ahead in the distance, you have to tell him so, which we did. I know this is a rather detailed message, but I wanted to try to clear this up for you. Did it work? If there is still any confusion, please let me know. I would love to know that it has clicked for you, because once it does, there will be no stopping you with regular expressions. Wishing you a beautiful day
  18. Yes! Exactly. UPDATE. I want: // double ** **, __ __, `` `` <--- need to be (stick together) Hi Andy, Just saw your update. So now you want doubles everywhere? Try this. <?php $s = 'There ___are__ few things which you ```need to ensure```` you would 1. educate (read all) 2. put into to use. ***Without those 2 points** you can be sure, that your depressio'; $s = preg_replace('/__(_*[^_]+_*)__/m', '<u>\1</u>', $s); $s = preg_replace('/\*\*(\**[^*]+\**)\*\*/m', '<b>\1</b>', $s); $s = preg_replace('/``(`*[^`]+`*)``/m', '<code>\1</code>', $s); echo htmlentities($s); ?> Pay attention to the test string, I have changed it so you can see how the regex behaves with extra quotes.
  19. Hi Andy, Try this. <?php $s = 'There ___are__ few things which you `need to ensure`` you would 1. educate (read all) 2. put into to use. ***Without those 2 points** you can be sure, that your depressio'; $s = preg_replace('/_(_*[^_]+_*)_/m', '<u>\1</u>', $s); $s = preg_replace('/\*\*(\**[^*]+\**)\*\*/m', '<b>\1</b>', $s); $s = preg_replace('/`([^`]+)`/m', '<code>\1</code>', $s); echo htmlentities($s); ?> Is that what you have in mind?
  20. Ah, now I get it. Thanks for explaining. I tested this code. It works for me, does it work for you? <?php $s = 'There ___are__ few things which you `need to ensure`` you would 1. educate (read all) 2. put into to use. ***Without those 2 points** you can be sure, that your depressio'; $s = preg_replace('/_([^_]+)_/m', '<i>\1</i>', $s); $s = preg_replace('/\*([^*]+)\*/m', '<b>\1</b>', $s); $s = preg_replace('/`([^`]+)`/m', '<code>\1</code>', $s); echo htmlentities($s); ?> Warmest wishes.
  21. Hi Debbie, To clarify: do you mean that it doesn't work, or that it looks strange to your eyes? (I have tested the php in the codebox. If you paste it in a php file, it should run.) Yes, "free-spacing mode", or "white-space mode", or simply (my favorite): "comment mode". As you can see in the code box, it has allowed me to write the regex on multiple lines instead of a single line. Also, it allows you to use comments (everything after a # on a line is a comment). It makes it a lot easier to read, lets it breathe. If you return to the code in a year, you will be able to understand the expression at one glance. You can see many more examples (with better formatting) on the tutorial in my signature. Not all regex flavors support this, but PCRE does, and PHP's preg functions use PCRE. If you use a space in the expression, you need to include it in a character class: [ ] You want at least one upper-case character, right? So this lookahead sees if anywhere on the string it can find ONE character between A and Z. The dot star is what enables the lookahead to look anywhere on the string: anything can precede the uppercase letter, including, potentially, nothing (allowed by the star). Does this clear it up for you? You seem interested, and I love regex, so I'm happy to keep answering any question you have about this expression. Warmest wishes
  22. How can you do: "`" that does <code> Hi Andy, I don't think I have any idea of what you mean there. Would you please explain?
  23. Wow, I went out to buy chocolate, and when I came back the war was over!!! Glad Sandeep was able to sort it out for you, Sean. On objects I definitely cannot help. Wishing you a beautiful end of the year.
  24. Hi Andy, I took a pass at your problem and tested the code below. Doing two replace operations in a row: one for the Italics, one for the Bold. The "plus quantifier" ensures we can have multiple underscores and stars. Last, the htmlentities in the echo ensure you can see the actual string in the html output (not the browser's rendering). <?php $s = 'There ___are__ few things which you `need to ensure`` you would 1. educate (read all) 2. put into to use. ***Without those 2 points** you can be sure, that your depressio'; $s = preg_replace('/_+([^_]*)_+/m', '<i>\1</i>', $s); $s = preg_replace('/\*+([^*]*)\*+/m', '<b>\1</b>', $s); echo htmlentities($s); ?> Is this what you're looking for? Wishing you a beautiful day.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.