Jump to content

JAY6390

Members
  • Posts

    825
  • Joined

  • Last visited

Posts posted by JAY6390

  1. <?php
    
    $str = "R1,R2-5,R7";
    $parts = explode(',', $str);
    $out = array();
    $regex = '~^([^\d]+)(\d+)-([^\d]*)(\d+)$~';
    
    foreach($parts as $part) {
    if(preg_match($regex, $part, $matches)) {
    	$range = range($matches[2], $matches[4]);
    	foreach($range as $number) {
    		$out[] = $matches[1] . $number;
    	}
    } else {
    	$out[] = $part;
    }
    }
    
    echo '<pre>' . print_r($out, true) . '</pre>';
    
    ?>

     

    That's how I would do it. Should work for your last example too

  2. You aren't going to be solving this using regex, at least not all of it. You're going to need to explode the values using the , then us a regex to match the 2-5, then use a for loop to iterate over the values and add them correctly to the array

  3. If you're wanting to restrict it to just text either side as the "tags" you could use

    function getTextBetweenTags($string, $start, $end) {
    $start = preg_quote($start, '~');
    $end = preg_quote($end, '~');
    $pattern = "~$start(.*?)$end~";
    
    if(preg_match($pattern, $string, $matches)) {
    	return $matches[1];
    }
    
    return false;
    }
    
    $html = 'this is a bunch of nothing _MARKER_OBJ = [ get this crap ]';
    
    $content = getTextBetweenTags($html, '_MARKER_OBJ = [', ']');
    
    echo $content;

     

    That doesn't require you to escape the start/end tags as it escapes all regex syntax characters using preg_quote

  4. Why would you use regex for this?

    Surely it's easier to just use regular php

     

    $age = (int) $_POST['age'];
    if($age >= 18 && $age <= 99) {
        // Age is correct
    } else {
        // Age is incorrect
    }

×
×
  • 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.