regex in preg_match_all() doesn't work as expected

I have the following string:

"<h2>Define Vim is the greatest</h2> word processor, good <h3>Vi</h3>!".

I want to select h2 and h3 like the following structure with a regex.

Expected output would be:

array( 0 => <h2>Define Vim is the greatviest</h2> 1 => <h3>Vi</h3> )

So I implement my regular expression as follow:

preg_match_all("/(?:<h2>|<h3>).*vi.*(?:<\/h2>|<\/h3>)/i", $input, $matches)

But instead of the desirable result as above, it outputs the following result.

Current output:

array( 0 => <h2>Define Vim is the greatviest</h2> word prviocessor ever created <h3>Vi</h3> )

How can I change my code/regex, so I get the tags as in the expected output above?

-------------Problems Reply------------

Well your problem is, that you first missing the delimiters for your regex and second vi is case-sensitive, so you would have to add the i flag, for case-insensitivity.

So your code could look something like this (Just removed the vi in the regex and now I just grab everything between h1-6 tags):

<?php

$input = '"<h2>Define Vim is the greatest</h2> word processor, good <h3>Vi</h3>!".';

preg_match_all("/(?:<h[0-6]>).*?(?:<\/h[0-6]>)/", $input, $matches);
print_r($matches);

?>

output:

Array
(
[0] => Array
(
[0] => <h2>Define Vim is the greatest</h2>
[1] => <h3>Vi</h3>
)

)

EDIT:

As from your updated regex now your problem is, that .* is greedy, means it takes as much as it can. To make it non-greedy you have to add a ? at the end. So just change your .* -> .*?.

Category:php Views:2 Time:2018-11-08

Related post

  • preg_match_all doesn't work as expected 2012-10-19

    I want to get matches on a webpage based on following regular expression: (.*) I tested it on regexpal.com (an online regular expression test tool) and it works fine. However, when I use it in php, I can't find any matches. The statement I use in php

  • Python Regex doesn't work as expected 2011-03-16

    i've crafted this regular expression: <entry>\\n<(\w+)>(.+?)</\w+>\\n</entry> to parse the following RSS Feed: <?xml version="1.0" encoding="UTF-8"?>\n<feed version="0.3" xmlns="http://purl.org/atom/ns#">\n<titl

  • Step Into Property/Function (F11) doesn't work as expected 2011-02-02

    In Visual Studio 2010, the Step Into Property/Function (F11) doesn't work as expected. It doesn't step into property setters or getters. I converted the solution from Visual Studio 2005 to 2010, the function i wanted to step into is a property in a s

  • IN Clause from an included table, doesn't works as expected 2011-12-02

    I'm trying to do this: var results = (from s in db.ExampleMaster .Include("State") .Include("Group") .Where("it.Group.IdGroup in {1,2,3,4,5}") .Where("it.IdState in {1,2}") select s); The Schema: ExampleMaster: IdExampleMaster int, IdState int State:

  • Typing into lookup field before new form finishes loading doesn't work as expected - crm 2011 online 2012-01-20

    We have a custom entity. When you create a new instance of this entity, it is defined such that the field that receives the initial focus is a lookup field of type customer. When using outlook client, create a new email, set regarding, custom entity,

  • Exec command doesn't work as expected 2012-02-22

    I'm trying to launch a CLI command from a PHP script: in particular I wanna use this command convert a.png a.tif to convert an image to tiff. When I launch this command from CLI it works as expected but if I launch from a PHP script with the followin

  • JQuery: animate() doesn't work as expected in IE 2008-12-02

    I'm getting crazy with this IE 7... ==> hhttp://neu.emergent-innovation.com/ Why does following function not work in IE 7, but perfectly with Firefox? Is there a bug in the animate-function? function accordion_starting_page(){ // hide all elements

  • Javascript regex multiline flag doesn't work 2009-07-01

    I wrote a regex to fetch string from html, but it seems the multiline flag doesn't work. this is my pattern and I want to get the text in h1 tag. var pattern= /<div class="box-content-5">.*<h1>([^<]+?)<\/h1>/mi m = html.search(pa

  • android:layout_gravity doesn't work as expected 2010-01-22

    I have a simple LinearLayout with one TextView and one ImageView. I want the text in the TextView to be aligned to the right, but the result show that the Text was aligned to the left. Is there anything wrong with my layout xml? Thanks. <?xml vers

  • Oracle regex: \Q\E doesn't work 2010-03-03

    I found that \Q\E doesn't work in oracle. What is the equivalent expression of \Q\E for oracle regex ? --------------Solutions------------- This is an old question, but with Java you can do Pattern.quote(yourString); which returns a literal string. S

  • My QFileSystemModel doesn't work as expected in PyQt 2010-04-17

    EDIT2: model.hasChildren(parentIndex) returns True, but model.rowCount(parentIndex) returns 0. Is QFileSystemModel just fubar in PyQt? EDIT: With a bit of adaptation this all works exactly as it should if I use QDirModel. This is deprecated, but mayb

  • Oracle Transactions doesn't work as expected in some client machines in a .net windows application 2010-09-02

    I have an windows application in VB.NET (2.0) and Oracle Database, the connections are handled by System.Data.OracleClient. My oracle client is 10g. In the server side, the AutoCommit is off. The application uses transtactions (isolationLevel: ReadCo

  • Zend Soap Server with wsdl autodiscovery doesn't work as expected 2011-02-18

    Duplicate of this question I'm trying to create a web service with Zend_Soap_Server in wsdl autodiscovery mode, but I obtain very strange effects... here the code: server: <?php require_once('Zend/Soap/AutoDiscover.php'); require_once('Zend/Soap/S

  • Moving the mouse cursor doesn't work as expected on X11 2011-03-13

    I'm trying to move the mouse pointer while the left button is down (Button1). But it doesn't work. For example, if I launch GIMP, I see a dot (cursor down), then the cursor moves but without drawing. I was expecting to see a drawn line (move while ho

  • problem with 3x3 3d rotation matrices logic - concatenation doesn't work as expected 2011-04-03

    In basic words I need a simple and fast algorithm to find the solution X from C * X = M where all variable are matrices. More explanations below. I'm trying to compute one specific matrix but it doesn't really work as expected: Vz - negative Z-axis v

  • MongoDB range search on numbers doesn't work as expected 2011-10-30

    I am trying to do a range search on some numbers in MongoDB. I have the following two records. The import fields are the last two, value and type. I want to be able to get records back that have a value: withing some range. { "_id" : ObjectId("4eace8

  • Regular Expression Lookbehind doesn't work as expected 2011-11-01

    I have a string in .net. <p class='p1'>Para 1</p><p>Para 2</p><p class="p2">Para 3</p><p>Para 4</p> Now, I want to get only text inside the tag p (Para 1, Para 2, Para 3, Para4). I used the following re

  • Operator -> doesn't work as expected in C++ 2012-01-03

    I was practicing single linked list in c++ (practicing how to find the beginning node of the circular list), but found the use of operator -> very confusing. I'm using Visual studio 2010 C++ Express This works perfectly: head->append(2)->app

  • How to keep core threads alive and die out excess threads in ThreadPoolExecutor? keepAliveTime doesn't work as expected 2012-01-05

    I use ThreadPoolExecutor to manage a thread pool. What we want are: if the pool has less than corePoolSize threads, kick off a new thread for a new task; if the pool has more than corePoolSize threads and all are busy, kick off a new thread for a new

  • POSIX C Threads. pthread_cond_t example. Doesn't work as expected 2012-04-16

    I wrote a wrote a program and it doesn't work as I expect it to. I have two threads: thread triggers func and anotherThread triggers anotherFunc. What I wanted to do is when cont reaches value 10 in func, anotherThread to be triggered using pthread_c

  • HTML5 Doctype + flex + overflow doesn't work as expected 2014-03-19

    I have: Style <style> html, body{ height:100%; } .layout{ display: box; padding: 20px; height: 95%; width: 95%; border-radius: 8px; -moz-box-orient: vertical; display: -moz-box; display: -webkit-box; -webkit-box-orient: vertical; } .layout-midd

  • requestedExecutionLevel requireAdministrator doesn't work as expected 2014-04-15

    I have an app.manifest file as following: <?xml version="1.0" encoding="utf-8"?> <asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft

  • addShutdownHook and setUncaughtExceptionHandler doesn't work as expected in java 2010-02-26

    I have a multi-threaded program, where I have one thread to watch over several threads. The functioning is designed like this: Main program does initiation and starts Watcher Thread, in void Main(), I have the line Runtime.getRuntime().addShutdownHoo

  • change/part doesn't work as expected with parse 2010-04-13

    According to http://www.rebol.com/docs/core23/rebolcore-15.html You can use change/part to parse and replace but that doesn't work well with this where I just try to replace the block <mytag > ... </mytag> by "MyString" content: {<myta

  • vertical-align:middle doesn't work as expected 2010-11-24

    I just want to place images in a fixed-height container: images must not exceed container's height and must be centered vertically. So I have <div id="partenaires"> <img src="images/partenaires/Debian.png" alt="Debian" /> <img src="ima

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.165 (s). 12 q(s)