1 . Replace all characters until backslash n times?

Answer :

You may use

preg_replace('~[^/]+/~', "---/", $string);
// => ---/---/---/---/2017-20190Course-Schedule.pdf

See the PHP demo.

See the regex demo here. Details:

  • [^/]+ - 1 or more chars other than /
  • / - a forward slash.

Note that / does not have to be escaped since ~ delimiters are used. The preg_replace function replaces all non-overlapping occurrences with the replacement pattern, ---/, so no need using a repeated capturing group (as in the original attempt).

Leave a Comment

1 . Codeigniter, join table properties overrides other properties?

Answer :

$this->db->select("*, questions.id as question_id");

It's obvious that properties with the same name will be overriden. That's why you should assign to them 'unique' names in select statement.

2 . May I choose php platform? Really is this feature true?

Answer :

 PHP has always been a wise choice because it runs on most Operating Systems. 
It has a massive library. 
It has massive contributions. 
It has been around for a long time. 
There is tons of add-ons, source code and support via user groups etc. 
The product is well maintained and well documented. 
It is easy to install and configure. 
It is free and Open Source. 
It interfaces well .. 

I can go on and on and on...... 

Java is equally, if not more, important to know. 
It can call PHP for Ajax type applications.

3 . From Javascript Date.now to PHP date?

Answer :

Date.now() in Javascript returns a timestamp in milliseconds, whereas Carbon's createFromTimestampmethod expects seconds.

There's a separate function you can use that accepts a millisecond-precision value. Try:

 $now = \Carbon\Carbon::createFromTimestampMs($request->input('time'));

4 . Multi Level user groups PHP Mysql while infinite loop?

Answer :

I don't understand what you tried to do in your last code, but it should work if you change echo $data['category'] = getCategories(0, $category); in your first code block to:

$data['category'] = "";
foreach (array_keys($category['parent_cats']) as $parent)
    $data['category'] .= getCategories($parent, $category);
echo $data['category'];

It does the same thing as you already did but multiple times with a different $parent every time for each cat.

5 . How to reorder buttons on page refresh in a form?

Answer :

This should work if you do not have an error in the database

    include_once 'dbconnect.php';

    $res=mysqli_query($con, "SELECT * FROM users WHERE user_id=".$_SESSION['user']);

    $array = array(
       $userRow['test1'] => array( 'class' => 'foo', 'name' => 'update' ),
        $userRow['test2']=> array( 'class' => 'john', 'name' => 'update' ),
        $userRow['test3'] => array( 'class' => 'x', 'name' => 'update' ),
        $userRow['test4'] => array( 'class' => 'a', 'name' => 'update' ),
        $userRow['test5'] => array( 'class' => 'b', 'name' => 'update' ),
        $userRow['test6'] => array( 'class' => 'c', 'name' => 'update' ),
        $userRow['test7'] => array( 'class' => 'd', 'name' => 'update' ),
        $userRow['test8'] => array( 'class' => 'e', 'name' => 'update' ),
        $userRow['test9'] => array( 'class' => 'f', 'name' => 'update' ),
        $userRow['test10'] => array( 'class' => 'g', 'name' => 'update' ),
        $userRow['test11'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test12'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test13'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test14'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test15'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test16'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test17'] => array( 'class' => 'h', 'name' => 'idchange' ),
        $userRow['test18'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test19'] => array( 'class' => 'h', 'name' => 'update' ),
        $userRow['test20'] => array( 'class' => 'h', 'name' => 'update' ),

    uksort( $array, function() { return rand() > rand(); } );

    foreach( $array as $item => $atts ){
        echo '<form action="check1.php" method="post">';
        echo '<div class="'. $atts['class'] .'"><button name="'. $atts['name'] .'" type="submit" >'. $item .'</button></div>';
        echo '</form>';

6 . How to insert and update the mysql table in php??????????

Answer :


$DBHost = "localhost"; 
$DBUser = "root"; 
$DBPass = ""; 
$DBName = "databaseName"; 

$con = mysql_connect($DBHost, $DBUser, $DBPass); 
$db = mysql_select_db($DBName, $con); 
CREATE TABLE IF NOT EXISTS `table_sample` ( 
`name` VARCHAR( 75 ) NOT NULL, 
`email` VARCHAR( 128 ) NOT NULL 
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;'); 

$sql = "INSERT INTO `table_sample` (`id`, `name`, `email`) 
VALUES (NULL,'YouName','emailidof the user'); 
$result = mysql_query($sql); 

$sql = "UPDATE `table_sample` SET `name` = 'Youname', `email` = 'emailidof the user' WHERE `id` = '2'; 
$result = mysql_query($sql); 

7 . Remove Woocommerce sidebar from any theme?

Answer :

The best and simple way that works with all themes is to use the get_sidebar Wordpress action hook this way:

add_action( 'get_sidebar', 'remove_woocommerce_sidebar', 1, 1 );
function remove_woocommerce_sidebar( $name ){
    if ( is_woocommerce() && empty( $name ) )

Code goes in function.php file of your active child theme (or active theme). Tested and works.

You might need to make some CSS changes on some html related containers

This code works on any theme as all themes use get_sidebar() Wordpress function for sidebars (even for Woocommerce sidebar) and get_sidebar action hook is located inside this function code.

8 . What is the difference between $GET, $POST, $REQUEST and $COOKIE in PHP?

Answer :

Those are predefined variables in php. 
when you send something from html code you need to chose method. Methods are get and post. 
<form action="example.php" method=(get or post)> 
<input type=text name='textfield'/> 

when you set the get method you can receive value in a example.php file using $_GET or $_REQUEST 

get method sends all information via url 
examle www.yahoo.com?ID=25 where id is variable with value 25. 
This is an example where you should use get. 
You have 2 limitations. 
1. The max value of characters you can send via url is 1024 including url 
2. If you enter password field with hidden characters it will be visible in url like 
www.yahoo.com?Username='Bojan';Passwor... so, do not use get for this. 

The post method is much more flexible for sending vulnerable kind of data because they travel in a hidden form. 
when you set the post method you can receive value in a example.php file using $_POST or $_REQUEST 

So, you can conclude that $_REQUEST is an universal variable to "catch" all sent data from html form. 

And $_COOKIE variable is an associative array of variables passed to the current script via HTTP Cookies.

9 . Custom cart item price calculation based on custom fields in Woocommerce?

Answer :
$total_price = ($height/3 * $width/30 + 3)*1.48;

As everything works, you will be able to make easily changes in your calculation if needed…

The code:

// Display custom input fields in single product page
add_action( 'woocommerce_before_add_to_cart_button', 'add_product_custom_fields', 20 );
function add_product_custom_fields(){
    $domain =  'woocommerce';
    $value = isset( $_POST['height_option'] ) ? sanitize_key( $_POST['height_option'] ) : '';
    printf( '<label>%s</label><input name="height_option" value="%s" type="number"/><br>', __( 'Height', $domain ), esc_attr( $value ) );

    $value = isset( $_POST['width_option'] ) ? sanitize_key( $_POST['width_option'] ) : '';
    printf( '<label>%s</label><input name="width_option" value="%s" type="number"/><br>', __( 'Width', $domain ), esc_attr( $value ) );

// Add custom fields data to cart items and make calculation price
add_filter( 'woocommerce_add_cart_item_data', 'custom_add_cart_item_data', 20, 2 );
function custom_add_cart_item_data( $cart_item, $product_id ){

    if( isset( $_POST['height_option'] ) )
        $cart_item['custom_data']['height'] = sanitize_key( $_POST['height_option'] );

    if( isset( $_POST['width_option'] ) )
        $cart_item['custom_data']['width'] = sanitize_key( $_POST['width_option'] );

    // Make calculation and save calculated  price
    if( isset( $_POST['height_option'] ) && isset( $_POST['width_option'] ) ){
        $height      = (int) sanitize_key( $_POST['height_option'] );
        $width       = (int) sanitize_key( $_POST['width_option'] );

        if( $width > 0 && $height > 0 ){
            $total_price = ( ( $height / 3 ) * ( $width / 30 ) + 3 ) * 1.48; // <== The calculation
            $cart_item['custom_data']['price'] = round($total_price, 2); // Save the price in the custom data

    return $cart_item;

// Display custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
function display_custom_cart_item_data( $cart_data, $cart_item ) {
    $domain = 'woocommerce';

    if ( isset( $cart_item['custom_data']['height'] ) ){
        $cart_data[] = array(
            'name' => __( 'Height', $domain ),
            'value' => $cart_item['custom_data']['height']
    if ( isset( $cart_item['custom_data']['width'] ) ){
        $cart_data[] = array(
            'name' => __( 'Width', $domain ),
            'value' => $cart_item['custom_data']['width']
    return $cart_data;

// Set the new calculated price replacing cart item price
add_action( 'woocommerce_before_calculate_totals', 'set_cart_item_calculated_price', 20, 1 );
function set_cart_item_calculated_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ){
        if( ! isset( $cart_item['custom_data']['price'] ) ){
        if( $cart_item['custom_data']['price'] > 0 ){
            // Set the calculated item price (if there is one)
            $cart_item['data']->set_price( (float) $cart_item['custom_data']['price'] );

// Get cart item custom data and update order item meta and display in orders and emails
add_action( 'woocommerce_checkout_create_order_line_item', 'save_order_item_custom_meta_data', 10, 2 );
function custom_add_order_item_meta( $item_id, $values ) {
    $domain = 'woocommerce';

    if( isset( $cart_item['custom_data']['height'] ) )
        $item->update_meta_data( __( 'Height', $domain ), $values['custom_data']['height'] );

    if( isset( $cart_item['custom_data']['width'] ) )
        $item->update_meta_data( __( 'Width', $domain ), $values['custom_data']['width'] );

Code goes in function.php file of your active child theme (or active theme).

10 . Php database creating acces denied,plz help me out.?

Answer :

include 'config.php'; 
include 'opendb.php'; 


include 'closedb.php'; 

If you want to create tables in the database you just created don't forget to call mysql_select_db() to access the new database. 

include 'config.php'; 
include 'opendb.php'; 

$query = 'CREATE DATABASE phpcake'; 
$result = mysql_query($query); 

mysql_select_db('phpcake') or die('Cannot select database'); 

$query = 'CREATE TABLE contact( '. 
'cname VARCHAR(20) NOT NULL, '. 
'cemail VARCHAR(50) NOT NULL, '. 
'csubject VARCHAR(30) NOT NULL, '. 
'cmessage TEXT NOT NULL, '. 
'PRIMARY KEY(cid))'; 

$result = mysql_query($query); 

include 'closedb.php'; 

11 . Multiple ajax requests from one page + how to do + best practice?

Answer :

google charts only needs to be loaded once per page load,
not every time you need to draw a chart

also, google.charts.load can be used in place of --> $(document).ready
it will wait for the page to load before executing the callback / promise

recommend setup similar to following snippet...

google.charts.load('current', {
  packages: ['corechart', 'bar']
}).then(function () {
    url: 'data.php',
    dataType: 'json'

    url: 'data.php',
    dataType: 'json'

function drawChart1(result) {

function drawChart2(result) {

12 . Why does Laravel Migrations on Windows migrates the first table but not the others?

Answer :

What is your version of mysql? as per documentation: If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider:

use Illuminate\Support\Facades\Schema;

 * Bootstrap any application services.
 * @return void
public function boot()

13 . PHP Programming is really good Language for Web Developing?

Answer :

PHP is a great language to know and is getting even better. 

Consider that there are now over 65 million WordPress installations on the web and there is no sign of it stopping anytime soon. WorPress is written in PHP and so are the themes that are making great money on the web. Also, PHP has come to the mobile platform creating yet another whole market for programming. Mobile used to be dominated by Java programmers but now that is changing. 

So the answer is yes, there is a long career opportunity in PHP programming and it pays well.

14 . Query function not work in php7?

Answer :

when I updated my PHP-scripts to PHP7 I had issues with


you should replace it with a function like


15 . Wired behaviour of .htaccess while i'm forcing to redirect https and skip /index.php in CodeIgniter 2.2.6?

Answer :

Try changing with the below, instead of

RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I have faced this like problems with the server cache for the 500 errors while editing the .htaccess, try with the incognito mode