0

I want to get some random code from URL beginning with some word (d_ and r_)

Example:

 1. domain.com/index/book-one-d_123456
 2. domain.com/index/book-one-r_123456

I want to show if the link is "d_123456" show content for "d_123456" and if "r_123456" show content for "r_123456". And explode random code after "d_" or "r_".

I have tried with:

if ($co){
$rand = explode('/',$co);

if (preg_match('/^.*([d_]).*?$/i', $rand[1]))
{
$res = explode("d_",$rand[1]);
some code..........
{
else if (preg_match('/^.*([r_]).*?$/i', $soid[1]))
{
$res = explode("r_",$rand[1]);
some code..........
}

I can get random code from "d_" but I can't get it working for "r_" or seems not detecting.


for I'm sorry I posted to early and Thanks for your help guys :D already found a solution from this post : https://stackoverflow.com/a/4366744/5118751

I just change :

if ($co){
$rand = explode('/',$co);

if (preg_match('/d_/', $rand[1]))
{
$res = explode("d_",$rand[1]);
some code..........
{
else if (preg_match('/r_/', $soid[1]))
{
$res = explode("r_",$rand[1]);
some code..........
}

and now everthing working perfect ...

Community
  • 1
  • 1
lllkyo
  • 3
  • 2
  • 4
  • 1
    But `$rand[1]` is going to be `index` which is not the delimiter you're looking for. Use `$rand[2]`. – LStarky Jan 08 '17 at 11:52

3 Answers3

1

I'm not sure if this is what you are looking for - the regex is quite crude.

$urls=array(
    'domain.com/index/book-one-d_123456',
    'domain.com/index/book-one-r_123456'
);

$pttn='@(.*)(d_(\d+))|(.*)(r_(\d+))@i';
foreach( $urls as $url ){

    preg_match( $pttn, $url, $matches );
    $matches=array_filter( $matches );
    if( !empty( $matches ) )print_r( array_values( $matches ) );
}

Will output:

Array
(
    [0] => domain.com/index/book-one-d_123456
    [1] => domain.com/index/book-one-
    [2] => d_123456
    [3] => 123456
)
Array
(
    [0] => domain.com/index/book-one-r_123456
    [1] => domain.com/index/book-one-
    [2] => r_123456
    [3] => 123456
)

From the output you can decide which items you wish to process further...

Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
0

Given your example URLs, $rand[1] is going to be index which is not the delimiter you're looking for. Use $rand[2] instead of $rand[1].

LStarky
  • 2,740
  • 1
  • 17
  • 47
0

I personally hate regex, so I believe there is a lot simpler way of doing what you need to do!

<?php
$url='domain.com/index/book-one-r_123456';
$ex=explode('_',$url);
    if(substr($ex[0],-1)=='d') { //checking if last letter is d
        //do some code, random code is $ex[2];, letter is d
    } elseif(substr($ex[0],-1)=='r') { //checking if last letter is r
        //do some code, random code is $ex[2]; letter is r
    }
?>

Good luck!

Danielius
  • 852
  • 5
  • 23