preg_match syntax - php

Studying some code from a codeigniter tut, the following preg_match pattern has me baffled:
preg_match('/js$/', $include)
What is the purpose of the $ after the js?
Thanks for the always thoughtful replies!
-----Complete Code-----
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Layouts Class. PHP5 only.
*
*/
class Layouts {
// Will hold a CodeIgniter instance
private $CI;
// Will hold a title for the page, NULL by default
private $title_for_layout = NULL;
// The title separator, ' | ' by default
private $title_separator = ' | ';
public function __construct()
{
$this->CI =& get_instance();
}
public function set_title($title)
{
$this->title_for_layout = $title;
}
public function view($view_name, $params = array(), $layout = 'default')
{
// Handle the site's title. If NULL, don't add anything. If not, add a
// separator and append the title.
if ($this->title_for_layout !== NULL)
{
$separated_title_for_layout = $this->title_separator . $this->title_for_layout;
}
// Load the view's content, with the params passed
$view_content = $this->CI->load->view($view_name, $params, TRUE);
// Now load the layout, and pass the view we just rendered
$this->CI->load->view('laytous/' . $layout, array(
'content_for_layout' => $view_content,
'title_for_layout' => $separated_title_for_layout
));
}
public function add_include($path, $prepend_base_url = TRUE)
{
if ($prepend_base_url)
{
$this->CI->load->helper('url'); // Load this just to be sure
$this->file_includes[] = base_url() . $path;
}
else
{
$this->file_includes[] = $path;
}
return $this; // This allows chain-methods
}
public function print_includes()
{
// Initialize a string that will hold all includes
$final_includes = '';
foreach ($this->includes as $include)
{
// Check if it's a JS or a CSS file
if (preg_match('/js$/', $include))
{
// It's a JS file
$final_includes .= '<script type="text/javascript" src="' . $include . '"></script>';
}
elseif (preg_match('/css$/', $include))
{
// It's a CSS file
$final_includes .= '<link href="' . $include . '" rel="stylesheet" type="text/css" />';
}
return $final_includes;
}
}
}

The dollar is an "end of string" anchor. The match will only succeed if "js" is at the end of the string.

Dollar sign means an end of line in regular expressions.

Related

add custom function to Codeigniter config such as site_url() & base_url()

we need to have a new function such as base_url() , named main_site_url() to being able to use it exactly as the same as site_url().
I've just added this to main config file in application/config:
$config['main_site_url'] = 'http//iksna.com/';
and this code to /system/core/config.php
/**
* Main Site URL
* Returns main_site_url . index_page [. uri_string]
*
* #access public
* #param string the URI string
* #return string
*/
function main_site_url($uri = '')
{
if ($uri == '')
{
return $this->slash_item('main_site_url').$this->item('index_page');
}
if ($this->item('enable_query_strings') == FALSE)
{
$suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix');
return $this->slash_item('main_site_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix;
}
else
{
return $this->slash_item('main_site_url').$this->item('index_page').'?'.$this->_uri_string($uri);
}
}
// -------------------------------------------------------------
but now, it is not accessible by: main_site_url();
is it accessible by: $this->config->main_site_url();
i have this error when is use main_site_url();
error:
Call to undefined function main_site_url()
You can create your own by the following way:
Step 1:
In you application/config/config.php add this, $config['main_site_url'] = 'http//iksna.com/';
Step 2:
In system/core/Config.php add a new function main_site_url() like base_url(), site_url() which are already defined there:
public function main_site_url($uri = '', $protocol = NULL)
{
$main_site_url = $this->slash_item('main_site_url');
if (isset($protocol))
{
if ($protocol === '')
{
$main_site_url = substr($main_site_url, strpos($main_site_url, '//'));
}
else
{
$main_site_url = $protocol.substr($main_site_url, strpos($main_site_url, '://'));
}
}
return $main_site_url.ltrim($this->_uri_string($uri), '/');
}
Step 3:
Now add the following code in system/helpers/url_helper.php
if ( ! function_exists('main_site_url'))
{
function main_site_url($uri = '', $protocol = NULL)
{
return get_instance()->config->main_site_url($uri, $protocol);
}
}
Now you can use main_site_url() anywhere in your controllers, libraries and views just like base_url(), site_url() etc.
Go to
/system/application/libraries
Create one file named
custom_function.php
add function main_site_url inside custom_function.php
call function in controller file using
$this->custom_function->main_site_url();

php: if current url contains "/demo" do something

I want to check if my current URL contains "/demo" at the end of the url, for example mysite.com/test/somelink/demo to do something.
Here is my attempt :
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'mysite.com/test/somelink/demo')
{
// Do something
}
else
{
// Do something
}
This seems to work fine, but the problem is that /somelink needs to by dynamic.
Any suggestion on how can I do this ?
Thank you !
Edit:
<?php
/* An abstract class for providing form types */
abstract class ECF_Field_Type {
private static $types = array();
protected $name;
/* Constructor */
public function __construct() {
self::register_type( $this->name, $this );
}
if(basename($_SERVER['REQUEST_URI']) == 'stats'){
echo "Hello World";
}
/* Display form field */
public abstract function form_field( $name, $field );
/* Display the field's content */
public function display_field( $id, $name, $value ) {
return "<span class='ecf-field ecf-field-$id'>"
. "<strong class='ecf-question'>$name:</strong>"
. " <span class='ecf-answer'>$value</span></span>\n";
}
/* Display field plain text suitable for email display */
public function display_plaintext_field( $name, $value ) {
return "$name: $value";
}
/* Get the description */
abstract public function get_description();
}
?>
Just use,
if(basename($_SERVER['REQUEST_URI']) == 'demo'){
// Do something
}
<?php
if (preg_match("/\/demo$/", $_SERVER['REQUEST_URI'])) {
// Do something
} else {
// Do something else
}
?>
This post has PHP code for simple startsWidth() and endsWith() functions in PHP that you could use. Your code would end up looking like:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith($host, '/demo'))
{
// Do something
}
else
{
// Do something
}
But one thing you might want to do in addition to that is convert $host to lowercase so the case of the URL wouldn't matter. EDIT: That would end up looking like this:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith(strtolower($host), '/demo'))
you can use strpos
$host = 'mysite.com/test/somelink/demo';
if(strpos($host,'demo'))
{
// Do something
echo "in Demo";
}
else
{
// Do something
echo "not in Demo";
}
$str = 'demo';
if (substr($url, (-1 * strlen($str))) === $str) { /**/ }

Writing 'one off' javascript in codeigniter

I'm in the process of working on my first code igniter project. I have some javascript that I need to write to initiate an instance of something on document ready. It's a one off, will never be called again. I need to include it in the head, but there may be a case where I need to do this at the end of the body. So, for example, lets say I have this:
<script>
alert('this is a one off alert');
</script>
What is the best practice in doing this stuff? Is it acceptable practice to put this in the controller? Does it need a model writing for it? Or do I need to create individual views for each script to be in MVC?
Thanks.
JS is part of HTML so it should not be in controller or in model, so it should be in view, as you are using framework then you should keep it in a separate file, you can have separate file for each method in your controller or one single JS file each controller.
also you can make a base_controller in your core folder and extend all your controller with it, there you can set all the default JS and CSS. so if you call an index method for a controller it will load with default JS and CSS and if need to add any new just pass it from the controller as John B said
You can have this function in your helper file
/**
* getting js files from public folder
* #param array $js
* #return string
*/
function js_tag($js) {
$out = "";
if (!empty($js)) {
$js = array_reverse($js);
foreach ($js as $j) {
if (strstr($j, "http:") == "" && strstr($j, "https:") == "") {
if ($j == 'tinymac') {
$out.='<script type="text/javascript" src="' . base_url() . 'jscripts/tiny_mce/tiny_mce.js"></script>' . "\n";
} else {
$out.='<script type="text/javascript" src="' . base_url() . 'public/js/' . $j . '"></script>' . "\n";
}
} else {
$out.='<script type="text/javascript" src="' . $j . '"></script>' . "\n";
}
}
}
$out .= '<script type="text/javascript"> var baseurl = "' . base_url() . '"</script>' . "\n";
return $out;
}
/**
* getting css files from public folder
* #author Amir M
* #param array $css
* #return string
*/
function css_tag($css) {
$out = "";
if (!empty($css)) {
$css = array_reverse($css);
foreach ($css as $c) {
if (strstr($c, "http:") == "" && strstr($c, "https:") == "") {
$out.= link_tag(base_url() . "public/css/" . $c) . "\n";
} else {
$out.= link_tag($c) . "\n";
}
}
}
return $out;
}
and you can call it from controller
public function index(){
$data['js'] = js_tag('one.js', 'two.js' , 'jquery.js');
$data['css'] = css_tag('one.css', 'two.css' , 'jquery-ui.css');
$thuis->load->view('index' , $data);
}
Note: the above method will reverse the array so the last value in the array will come first on the page so keep the jQuery last in the array
in the header which is common on all website
<?php echo $js.$css?>
generally the practice I use is this:
All view files load a common header. And the view files are loaded at the end of the controller.
You can either hardcode or pass the links for scripts you want to initiate from the controller. Hardcoding the script tags is self explanatory. If you want to do it a bit more dynamically, you could set up an array of script sources and just loop through them in the header.
so in the controller
$data['scripts'] = array();
$data['scripts'][] = 'http://yoursourcehere';
or if self hosting:
$data['scripts'][] = site_url('assets/js/yourscript.js');
then the view
if(isset($scripts))
{
foreach($scripts as $script)
{
echo '<script type="text/javascript" src="'.$script.'"></script>';
}
}
so basically you can just put all your custom script in a separate file an load it this way. Its practical because it can load all your scripts at once in a common way.

Code igniter Themes' library.

I need 3 different templates for my Codeigniter application. I had read about Themes' library. But still I didn't get any idea about how to add a template to Codeignier ..
I got about how to involke template in Controller .
Please help
I'm using this template library, is really simple and works well for me.
application/libraries/Template.php
<?php
class Template {
var $template_data = array();
var $use_template = '';
/**
* Set variable for using in the template
*/
function set($name, $value)
{
$this->template_data[$name] = $value;
}
/**
* Set template name
*/
function set_template($name)
{
$this->use_template = $name;
}
/**
* Load view
*/
function load($view = '' , $view_data = array(), $template = '', $return = FALSE)
{
$this->CI =& get_instance();
if (empty($template)) {
$template = $this->CI->config->item('template_master');
}
if (!empty($this->use_template)) {
$template = $this->use_template;
}
$this->set($this->CI->config->item('data_container'), $this->CI->load->view($view, array_merge($view_data, array ('template' => $this->template_data)), true));
return $this->CI->load->view($this->CI->config->item('template_folder') . '/' . $template, $this->template_data, $return);
}
}
application/config/template.php
<?php
$config['template_master'] = 'main';
$config['template_folder'] = 'templates';
$config['data_container'] = 'content';
application/views/templates/main.php
Header<br />
<?php echo $content; ?></br>
Footer
application/controllers/welcome.php
<?php
class Welcome extends CI_Controller
{
public function index()
{
$this->load->config('template');
$this->load->library('template');
$this->template->load('welcome', array('view' => 'data'));
}
}
I usually put the config/library files on autoload, and you can use anytime $this->template->set_template('other_template'); to use another one :)
Hope it helps.
I've used the following setup in a CodeIgniter project:
The different templates along with stylesheets and images are in the following folder:
/templates/1/header.php
/templates/1/footer.php
/templates/1/images/*
/templates/1/style/*
/templates/2/header.php
/templates/2/footer.php
/templates/2/images/*
/templates/2/style/*
In your Controllers determine which template you want to load and pass the path to that template as a variable ( templatepath in this case ) to your View files. Inside the view files you do the following:
<?php include($templatepath.'/header.php'); ?>
at the top and
<?php include($templatepath.'/footer.php'); ?>
at the bottom.

PHP class doesn't echo another php page at the appropriate place

Alright, I'm using a page creating class I found as below but when I want to use a php page -that again includes and uses a class file- for the content it either echoes on the top or the bottom of the page... I even tried to make the page a function() and call it at the $Content string but no use, again it echoed on the top of the page... How can i use a php page as a content in this class, or what should i change to use a php file?
Please keep in mind that I'm new to classes so feel free to assume some beginner mistakes.
<?php
class Page {
var $Title;
var $Keywords;
var $Content;
function Display( ) {
echo "<HTML>\n<HEAD>\n";
$this->DisplayTitle( );
$this->DisplayKeywords( );
echo "\n</HEAD>\n<BODY>\n";
echo $this->Content;
echo "\n</BODY>\n</HTML>\n";
}
function DisplayTitle( ) {
echo "<TITLE>" . $this->Title . "</TITLE>\n";
}
function DisplayKeywords( ) {
echo '<META NAME="keywords" CONTENT="' . $this->Keywords . '">';
}
function SetContent( $Data ) {
$this->Content = $Data;
}
}
?>
Usage:
<?php
include "page.class";
$Sample = new Page;
$Content = "<P>I want my php file's contents here.</P>";
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent( $Content );
$Sample->Display( );
?>
What if I wanted to make the content something like $Content = " < ? echo 'test'; ? >"; I know this isn't valid but what i'm trying to do is something like that or something like $Content = " output of the whateversinhere.php ";. how should I object orient another page therefore getting its contents into a string here?
You should NOT echo anything inside your class, instead the class should have a method getMarkup(), which will return a string containing the whole markup. Then you can echo that string in your view.
Additional tipps:
variables and method names start with a small letter!
title and keywords should have getters and setters too
make your variables private (private $title, etc.)
let me clean this up for you, you will notice some changes:
class Page
{
private $title = 'No Title';
private $keywords = array();
private $content = '';
public function setTitle($title)
{
$this->title = (string)$title;
}
public function addKeywords($keywords)
{
$this->keywords = array_merge($this->keywords, (func_num_args() > 1) ? func_get_args() : (array)$keywords;
}
function setContent($content)
{
$this->content = $content;
}
function appendContent($content)
{
$this->content .= $content;
}
function prependContent($content)
{
$this->content = $content . $this->content;;
}
private function display()
{
/*
* Display output here
*/
echo $this->title;
echo implode(',',str_replace(',','',$this->title));
echo $this->contents;
}
}
pretty simple usage:
$Page = new Page;
$Page->setTitle("Hello World");
$page->addKeywords("keyword1","keyword2","keyword3","keyword4");
//Content
$this->setContent("World");
$this->prependContent("Hello");
$this->appendContent(".");
//Display
$this->display();
Just got to fill in the blanks, you will learn as time goes on that you should not be using html directly within your class, and that you would split the above into several class such as Head,Body,Footer,Doctype and have a page class that brings them all together.
Use Output Control Functions.
<?php
include "page.class";
$Sample = new Page;
ob_start();
include "foobar.php";//What you want to include.
$content = ob_get_contents();
ob_end_clean();
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent($content);
$Sample->Display( );
?>

Categories