...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
July 9, 2012

Replacing keywords with similar content

Question by Samson

With a list of keywords like in the array below:

$keywordlist = array(
    'Apple iPhone' => 'http://www.example.com/apple/iphone/',
    'Apple iPad' => 'http://www.example.com/apple/ipad',
    'Samsung Galaxy Ace' => 'http://www.example.com/samsung/galaxy-ace',
    'Samsung Galaxy Nexus' => 'http://www.example.com/samsung/galaxy-nexus',
    'Samsung' => 'http://www.example.com/samsung/',
    'Apple' => 'http://www.example.com/apple/'
);

I want to replace the keywords with the URLs associated with them.

I’ve tried looping through them and use str_replace and preg_replace, but this is replacing the manufacturers name in all keywords, so all the keywords get turned into links for just ‘Samsung’ and ‘Apple’. I’m a bit stumped as to where to head next, anyone got any pointers?

Edit:

I used the below code to loop through –

foreach($keywordlist as $name => $link){ 
    $content = str_replace($name, '<a href="'.$link.'">'.$name.'</a>', $content);
}

Solution:

I believe the problem was the link text I was replacing. It was then being replaced again by the other phrases with similar keywords, I’ve got the below to work.

Anyone think of a better way of doing this?

$content = "<p>This Apple iPhone is from Apple</p>
            <p>This Apple iPad is from Apple</p>
            <p>This Samsung Galaxy Ace is from Samsung</p>
            <p>This Samsung Galaxy Nexus is from Samsung</p>
            <p>This is a Samsung</p>
            <p>This is an Apple</p>";



$keywordlist = array(
    'Apple iPhone' => '[1]',
    'Apple iPad' => '[2]',
    'Samsung Galaxy Ace' => '[3]',
    'Samsung Galaxy Nexus' => '[4]',
    'Samsung' => '[5]',
    'Apple' => '[6]'
);

$content = str_replace(array_keys($keywordlist), array_values($keywordlist), $content);

$urllist = array(
    '[1]' => '<a href="http://www.example.com/apple/iphone/">Apple iPhone</a>',
    '[2]' => '<a href="http://www.example.com/apple/ipad">Apple iPad</a>',
    '[3]' => '<a href="http://www.example.com/samsung/galaxy-ace">Samsung Galaxy Ace</a>',
    '[4]' => '<a href="http://www.example.com/samsung/galaxy-nexus">Samsung Galaxy Nexus</a>',
    '[5]' => '<a href="http://www.example.com/samsung/">Samsung</a>',
    '[6]' => '<a href="http://www.example.com/apple/">Apple</a>'
);

$content = str_replace(array_keys($urllist), array_values($urllist), $content);

echo $content;

Output:

This Apple iPhone is from Apple

This Apple iPad is from Apple

This Samsung Galaxy Ace is from Samsung

This Samsung Galaxy Nexus is from Samsung

This is a Samsung

This is an Apple

Answer by Starx

str_replace() should be enough for what you are attempting.

foreach($keywordlist as $key => $link) {
     $content = str_replace($key, '<a href="$link">$key</a>', $content);
}

As, I have commented, this will not work as expected because of the repeated duplicate keywords on the keys.

You need to have a fixed format to denote a key. The one I suggest is something like [Apple] and [Apple iPad]. When you implement something similar to this, every keyword will be different, although they contain same inner code inside.

Your updated keyword structure will look something this, after wards.

$keywordlist = array(
    '[Apple iPhone]' => 'http://www.example.com/apple/iphone/',
    '[Apple iPad]' => 'http://www.example.com/apple/ipad',
    '[Samsung Galaxy Ace]' => 'http://www.example.com/samsung/galaxy-ace',
    '[Samsung Galaxy Nexus]' => 'http://www.example.com/samsung/galaxy-nexus',
    '[Samsung]' => 'http://www.example.com/samsung/',
    '[Apple]' => 'http://www.example.com/apple/'
);

If this, options is not feasible to use, as this significantly increase the complexity while developing the content, as needing to wrap every keyword text with [].

Read more

Touchscreen media-queries

Question by JJ56

What is the safest way, using media queries, to make something happen when not on a touchscreen device? If there is no way, do you suggest using a javascript solution such as !window.Touch or modernizer?

Thanks in advance!

Answer by Starx

I would suggest using modernizr and using its media query features.

if (Modernizr.touch){
   // bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
   // bind to normal click, mousemove, etc
}

However, using CSS, there are psedo class like, for example in firefox. You can use :-moz-system-metric(touch-enabled). But these features are not available for every browswers.

For Apple devices, you can simple use:

if(window.TouchEvent) {
   //.....
}

Specially for Ipad

if(window.Touch) {
    //....
}

But, these do not work on Android.

Modernizr gives feature detection abilities, and detecting features is
a good way to code, rather than coding on basis of browsers.

Read more
July 8, 2012

manage module's options approach

Question by mhesabi

I’m about to create let say a custom CMS with php and mysql. each page has a few zones. each zone can output modules. for example we have a news module and we already added news categories and single news items at module admin section.
but here it begin: end user wants to get different output of this module. for example user wants to show news of “sport” category, or user wants to show top 5 last news, or user wants to sort news by something, or, or, or …. many other options that a module can take.

my question is what is your solution to handle and manage these options.
– do you suggest a module_option table for every module like news_options?
– do you suggest a single table that holds every modules options?

hope I could get what i mean 😉 also let me know if db diagram is necessary.

Answer by Starx

  1. First approach could be using different table for each module. Then you can keep the settings of different instance in the fields. In the manageable form.

    Example:

    Table: News
    ----------------------------------------------------------------------
    | id      +     news_title     +     option 1     +    option 2      |
    ----------------------------------------------------------------------
    
  2. Next approach, could me using Global configuration table, which holds the key name and one field and key value in another field. This way you dont have to create different table from different modules.

    Example:

    Table: ModuleOption

    --------+-----------------+-------------------+---------------------+
    |  id   |   module_id     |    setting_name   |   settings_value    |
    --------+-----------------+-------------------+---------------------+
    |   1   |   1             |     option 1      |   option value 1    |
    --------+-----------------+-------------------+---------------------+
    |   2   |   1             |     option 2      |   option value 2    |
    --------+-----------------+-------------------+---------------------+
    

The questions about which one to choose over which, depends on how you code your project. Both have its own advantages and disadvantages. However, some points to consider

  • If the option contains a method to input long text then, second approach is bad as the size of options will vary a lot.
  • If all the module settings can accompany with in fixed length fields, then second option is definitely the best way.
Read more

Scrolling to a particular div

Question by user1510326

I have an html page with three divs containing text content. I want to scroll to a particular div depending upon the link that the user clicks on the home page.

There are three links on the home page; so what I want is if the user clicks on link 1 he is scrolled to div 1 on the resultant page, if he clicks on link 2 on the home page, then the page is scrolled to div 2 on resultant page and so on.

Answer by Starx

Easiest method is using Fragment Identifier. Whenever you are creating links, attach the id of the element you want to scroll to, on the end of link. For example:

link.html#divToScrollTo

An example usage:

<a href="link.html#divToScrollTo">Scroll to div with divToScrollTo as id</a>

After clicking on this link, the browser to first navigate to link.html and then scroll to an element with divToScrollTo Link.

Read more
July 5, 2012

Cancel Redirect in Javascript?

Question by Elite Gamer

i added this to the head of my page:

<script type="text/javascript">

if (screen.width <= 800) {
    window.location = "http://m.domain.com";
}

</script>

i have a button on my mobile version called “Main Site”.
I want the button to go to my main site, but not redirect back to my mobile site. How do i do this?

also, i only want them to go there once. So, the next time they enter my website name, i want it to take them to mobile site

Answer by Starx

If you already have a button to go your main site. Just link the main site to that button. What you can do extra is, use an url parameter to check and force the main layout. Something like

<a href="http://www.domain.com?forcelayout=main">Main site</a>

Check for this parameter, when you want to force the main layout. Or else, the script currently using will automatically do what you want to do.


Use the following function to read the query string. [Source]

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/+/g, ' '));
}

Next you can use it in your logic, like this:

if (screen.width <= 800 && getParameterByName('forceLayout') != 'main') {
    window.location = "http://m.domain.com";
}
Read more
July 4, 2012

What is CSS hooks and what are very common css hooks

Question by MAK Ripon

I have been introduced with the term css hooks but I am not much clear about that. Could you give me some idea.

  • what is CSS hooks ?
  • what are the common hooks?
  • what are the best practices to use css hooks?

Any kind of example and relevant links are highly appreciable.

Answer by Starx

What is CSS Hooks?

CSS Hooks is a simple mechanism, which defines a way for your element to retrieve its styles from a third source.

What are the common hooks?

There are not any. Variation lies in your imagination.

What are the best practices to use CSS Hooks?

Look into JQuery.cssHooks.

Read more

Prevent alert boxes from appearing in Firefox

Question by Trevor Roberts

I can use this in my Opera browser to stop the alert boxes from appearing:

javascript:function alert () {}

However, it does not work whenever I use this in Firefox. What is the command to stop the alerts in Firefox?

Answer by Starx

This can be done like this

window.alert = function() { return false; }

But, if you want to stop the alert boxes, best solution is not to use alert() at all.
Disabling the JavaScript functions in not right solution.

Read more

MySQL – when to use single quotes, double quotes, and backticks?

Question by Nate

I’ve been reading answers to similar questions on here for about 20 minutes, but it seems like there is no definitive answer to this question.

I am a newbie PHP programmer and am trying to learn the best way to write queries. I also understand the importance of being consistent, and up until now I have essentially randomly used single quotes, double quotes, and backticks without any real thought.

Example:

$query = 'INSERT INTO table (id, col1, col2) VALUES (NULL, val1, val2)';

Also, in the above example, consider that "table," "col[n]," and "val[n]" may be variables.

What is the standard for this? What do you do?

Thanks for your advice.

Answer by Michael Berkowski

Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword.

Single quotes should be used for string values like in the VALUES() list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.

So using your example, I would double-quote the PHP string and use single quotes on the values 'val1', 'val2'. NULL is a MySQL keyword, and a special (non)-value, and is therefore unquoted.

None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I’ve quoted them anyway with backticks.

$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, 'val1', 'val2')";
//---------------------------------------------------------------^^^^^^^^^^^^^^^^ Single-quoted strings
//----------------------------------------------------------^^^^^ Unquoted keyword
//-------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Backtick table & column

The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL.

// Same thing with some variable replacements
$query = "INSERT INTO `$table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

According to MySQL documentation, you do not need to quote (backtick) identifiers using the following character set:

ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)

You can use characters beyond that set as table or column identifiers, but then you must quote (backtick) them.

Answer by Starx

Backticks are generally used to indicate an identifier and as well be safe from accidentally using the Reserved Keywords.

For example:

Use `database`;

Here the back ticks will help the server to understand that the database is infact the name of the database, not the database identifier.

Same can be done for the table names and field names. This is very good habit if you wrap your database identifier with a backticks.

Check this answer to understand more about backticks.


Now about Double quotes & Single Quotes (Michael has already mentioned that).

But, to define a value you have to use either single or double quotes. Lets see another example.

INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, title1);

Here I have deliberately forgot to wrap the title1 with a quotes. Now the server will take the title1 as a column name (i.e. an identifier). So, to indicate its a value you have to use either double or single quotes.

INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, 'title1');

Now, in combination with PHP, double quotes and single quotes make your query writing time so easier. Lets see a modified version of the query in your question.

$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

Now, using double quotes in the PHP, you will make the variables $val1, and $val2 to use their values thus creating a perfectly valid query. Like

$val1 = "my value 1";
$val2 = "my value 2";
$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

Will make

INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, 'my value 1', 'my value 2')
Read more
July 3, 2012

How to make the <img> tags line up horizontally in the div?

Question by justcode

I need to make the images show up side by side horizontally in the div. How can I do that?

HTML:

<div class="Wrapper">
  <img src="/wp-content/uploads/2012/07/TFT.png" alt="Smiley face" height="90" width="95" />
  <img src="/wp-content/uploads/2012/07/Ltyt.png" alt="Smiley face" height="90" width="95" />
  <img src="/wp-content/uploads/2012/07/artspng" alt="Smiley face" height="90" width="95" />
</div>

Reference: jsFiddle

Answer by Ravi

You could also use css properties display:inline-block or float : left to achieve this.

HTML Code

<div>
    <img ... />
    <img ... />
    <img ... />
</div>

CSS Code

div img{ display: inline-block;}

or

div img{ display: block;float: left;margin-right: 5px;}

Answer by Starx

On the general assumption of your code being something like this

<div>
    <img ... />
    <img ... />
    <img ... />
</div>

Then, a simple CSS property will get the job done.

div img { display: inline; }

On seeing your HTML portion. You can use the following CSS to get them online.

.partners img { display: inline; }
Read more
July 2, 2012

100% left div section required

Question by user1356607

I have two divs (red and yellow). Red div has 100% height and Yellow div in fixed 1000 pixel. I want red div 100% of the window screen even I scroll down the page, but it is not taking 100% height of the browser screen. I tried to find so many examples but failed to resolve my issues. Please guide…

Here is the example i have done.

http://jsfiddle.net/awaises/Ff6v5/

Answer by Mateusz Kocz

Is this what you want?

Then you need to change three things:

  1. body’s and html’s height to min-height;
  2. body’s and html’s position to relative;
  3. you don’t need !important in .left-menu’s height.

Answer by Starx

It doing what it is suppose to do !!!

This is really a misunderstanding.

Your style of height: 100% applies to .left-menu. But inside this .left-menu, you have another div called .left-footer, which has green as its background. So, the CSS is doing what is coded to do.

It order to span the red above the entire left area, you dont have to do anything. It is already doing that. For the proof see this.

So, there is nothing to fix. This is a design flaw.

Read more
...

Please fill the form - I will response as fast as I can!