如何使用PHP在两个可变部分中转换我的URL?

I want to convert my URLs into two parts e.g I have 4 urls like

  • c/category1
  • c/category2
  • p/page1
  • p/page2

Now what I extractly want is to convert URLs into two parts e.g.

$veriable_name1 = c
$veriable_name2 = category 1

or

$veriable_name1 = c
$veriable_name2 = category 2

or

$veriable_name1 = p
$veriable_name2 = page 1

or

$veriable_name1 = p
$veriable_name2 = page 2

In above examples C determines category and P determines Page. As i followed a tutorial to convert PHP urls into SEO friendly urls with PHP, but they only gave an example to convert urls by using PHP/MySQL from single table.

The code which i followed:

<?php
include('db.php');
if ($_GET['url']) {
    $url = mysql_real_escape_string($_GET['url']);
    $url = $url.'.html'; //Friendly URL 
    $sql = mysql_query("select title,body from blog where url='$url'");
    $count = mysql_num_rows($sql);
    $row = mysql_fetch_array($sql);
    $title = $row['title'];
    $body = $row['body'];
} else {
    echo '404 Page.';
} ?>

HTML Part

<body>
<?php
if ($count) {
    echo "<h1>$title</h1><div class='body'>$body</div>";
} else {
    echo "<h1>404 Page.</h1>";
} ?> 
</body>

but i have multiple links on my page and want to extract from multiple tables if other best suggestions

You need something like this:

$url = "c/category1";

$str_pos = strpos($url, "/");
$url_1 = substr($url, 0, $str_pos);
$url_2 = substr($url, $str_pos+1);

echo $url_1."<br/>";
echo $url_2;

Result:

c
category1

All your example "strings" are quite equal, so the easiest thing to do will be:

$url = 'c/category1';
$a = explode('/',$url);

$veriable_name1 = $a[0];
$veriable_name2 = $a[1];

or, to keep it a string function, you could run

$variable_name1 = strstr($url,'/',true);
$variable_name2 = str_replace('/','',strstr($url,'/'));

You can use explode for that:

    $str = "c/category1";
    list($variable_name1, $variable_name2) = explode('/', $str, 2);

    var_dump($variable_name1);
    var_dump($variable_name2);

//Output:
//string(1) "c" string(9) "category1"

U can use explode fn to do this. I have tried with strstr function.

Reference to strstr fn http://php.net/manual/en/function.strstr.php

$str  = 'c/category';
$var2 = trim(strstr($str, '/'),'/');
echo $var2; // prints category
$var1 = strstr($str, '/', true); // As of PHP 5.3.0
echo $var1; // prints c

Note: it is applicable for [single slash oly] like c/category not for c/category/smg

You can also use a regular expression:

$url = "c/category1";

preg_match('/^(.+)\/(.+)$/', $url, $matches);

// check that the URL is well formatted:
if (count($matches) != 3) {die('problem');}

$veriable_name1 = $matches[1];
$veriable_name2 = $matches[2];
echo('"'.$veriable_name1.'" | "'.$veriable_name2.'"');
// it will show this: "c" | "category1"

Test the regex online [regex101.com].