Category Archives: String Manipulation

Mass Mailer Sender PHP String Manipulation

This is a simple but very usefull Mass Mailer Sender script, that you can use from your server to send mass mails.You can for example use it to send annoncements for your members, that you have an offer for them. You can also use it as mass mailer subscriber to send weekly mails to yours subcribers.

<?

 include "header.php";
 include "config.php";

 if(isset($_POST['submit']))
 {
 $seconds=$_POST['seconds'];
 $subject=$_POST['subj'];
 $messagesend=$_POST['message'];
 mysql_connect($server, $db_user, $db_pass)
 or die ("Database CONNECT Error");
 $resultquery = mysql_db_query($database, "select * from $table");

 while ($query = mysql_fetch_array($resultquery))
 {
 $emailinfo=$myemail;
 $mailto=$query[$table_email];
 mail($mailto, $subject, $messagesend , "From:".$fromadmin."\nReply-To:".$fromadmin."\n");
 echo 'Mail sent to '.$mailto.'<br>';
 sleep($seconds);
 }
 echo 'Mails sent. Go <a href="massmail.php">Back</a>';
 }
 else
 {
 ?>
<table height="250" cellpadding="1">
<tr><td valign="top">
<h2>Free Mass Mail Sender</h2><br><form action="massmail.php" method="POST">

 <div align="center">
 <table cellpadding="0" border="0" align="left">
 <tr>
 <td>
 Subject:
 </td>
 <td>
 <input type="text" align="left" name="subj" size="66">
 </td>

 </tr>
 <tr><td align="left" valign="top">
 Message Text:</td><td align="left"> <textarea name="message" rows="15" cols="60"                ></textarea></td></tr>
 <tr>
 <tr><td colspan="2" align="left">
 Seconds between messages:<input type="text" size="10" name="seconds" value="0.1"> (seconds)
 </td></tr>
 <tr><td colspan="2">
 <input type="submit" value="Send mass mails" name="submit" >
 </Td>
 </tr>

 </table>
 </div>
</td>
</tr>
</table>

 <?
 }
 include "footer.php";
?>

&amp;nbsp;

PHP / MySQL.Fetch Associative Array.s Manipulation

MySQL doesn’t have a Fetch Array function. mysql_fetch_array is actually a PHP function that allows you to access data stored in the result returned from a successful mysql_query. If you have been jumping around our MySQL Tutorial then you would have already seen this function popping up all over the place.

 

<?php

 $conn = mysql_connect("localhost",  "mysql_user",  "mysql_password");

 if (!$conn) {
 echo "Unable to connect to DB: " . mysql_error();
 exit;
 }

 if (!mysql_select_db("mydbname")) {
 echo "Unable to select mydbname: " . mysql_error();
 exit;
 }

 $sql = "SELECT id as userid,  fullname,  userstatus
 FROM   sometable
 WHERE  userstatus = 1"
;

 $result = mysql_query($sql);

 if (!$result) {
 echo "Could not successfully run query ($sql) from DB: " . mysql_error();
 exit;
 }

 if (mysql_num_rows($result) == 0) {
 echo "No rows found,  nothing to print so am exiting";
 exit;
 }

 // While a row of data exists,  put that row in $row as an associative array
 // Note: If you're expecting just one row,  no need to use a loop
 // Note: If you put extract($row); inside the following loop,  you'll
 //       then create $userid,  $fullname,  and $userstatus
 while ($row = mysql_fetch_assoc($result)) {
 echo $row["userid"];
 echo $row["fullname"];
 echo $row["userstatus"];
 }

 mysql_free_result($result);

?>

&amp;nbsp;

&amp;nbsp;

PHP benchmark Script String Manipulation

This free PHP performance benchmark script is a free PHP script to calculate benchmark speeds (PHP execution times) of PHP web hosting servers. The free PHP script performs some simple mathematics and string manipulating functions repetitively, and records the PHP code execution time it takes to complete the PHP functions.

 

<?php
/*
##########################################################################
#                      PHP Benchmark Performance Script                  #
#                         © 2010 Code24 BV                               #
#                                                                        #
#  Author      : Alessandro Torrisi                                      #
#  Company     : Code24 BV, The Netherlands                              #
#  Date        : July 31, 2010                                           #
#  version     : 1.0                                                     #
#  License     : Creative Commons CC-BY license                          #
#  Website     : http://www.php-benchmark-script.com                     #
#                                                                        #
##########################################################################
*/


 function test_Math($count = 140000) {
 $time_start = microtime(true);
 $mathFunctions = array("abs", "acos", "asin", "atan", "bindec", "floor", "exp", "sin", "tan", "pi", "is_finite", "is_nan", "sqrt");
 foreach ($mathFunctions as $key => $function) {
 if (!function_exists($function)) unset($mathFunctions[$key]);
 }
 for ($i=0; $i < $count; $i++) {
 foreach ($mathFunctions as $function) {
 $r = call_user_func_array($function, array($i));
 }
 }
 return number_format(microtime(true) - $time_start, 3);
 }


 function test_StringManipulation($count = 130000) {
 $time_start = microtime(true);
 $stringFunctions = array("addslashes", "chunk_split", "metaphone", "strip_tags", "md5", "sha1", "strtoupper", "strtolower", "strrev", "strlen", "soundex", "ord");
 foreach ($stringFunctions as $key => $function) {
 if (!function_exists($function)) unset($stringFunctions[$key]);
 }
 $string = "the quick brown fox jumps over the lazy dog";
 for ($i=0; $i < $count; $i++) {
 foreach ($stringFunctions as $function) {
 $r = call_user_func_array($function, array($string));
 }
 }
 return number_format(microtime(true) - $time_start, 3);
 }


 function test_Loops($count = 19000000) {
 $time_start = microtime(true);
 for($i = 0; $i < $count; ++$i);
 $i = 0; while($i < $count) ++$i;
 return number_format(microtime(true) - $time_start, 3);
 }


 function test_IfElse($count = 9000000) {
 $time_start = microtime(true);
 for ($i=0; $i < $count; $i++) {
 if ($i == -1) {
 } elseif ($i == -2) {
 } else if ($i == -3) {
 }
 }
 return number_format(microtime(true) - $time_start, 3);
 }


 $total = 0;
 $functions = get_defined_functions();
 $line = str_pad("-",38,"-");
 echo "<pre>$line\n|".str_pad("PHP BENCHMARK SCRIPT",36," ",STR_PAD_BOTH)."|\n$line\nStart : ".date("Y-m-d H:i:s")."\nServer : {$_SERVER['SERVER_NAME']}@{$_SERVER['SERVER_ADDR']}\nPHP version : ".PHP_VERSION."\nPlatform : ".PHP_OS. "\n$line\n";
 foreach ($functions['user'] as $user) {
 if (preg_match('/^test_/', $user)) {
 $total += $result = $user();
 echo str_pad($user, 25) . " : " . $result ." sec.\n";
 }
 }
 echo str_pad("-", 38, "-") . "\n" . str_pad("Total time:", 25) . " : " . $total ." sec.</pre>";

?>

&amp;nbsp;

&amp;nbsp;

Generate PDFs with PHP Article Manipulation

One of the reasons I like PHP so much is its consistent support for new technologies. The language invites extensibility, making it easy for developers to add new modules to the core engine, and widespread community support has made PHP one of the most full-featured Web programming languages around, with support for a wide variety of modular extensions.

 

<ol>
    <li><?php</li>
    <li> create handle for new PDF document $pdf = pdf_new();</li>
    <li> open a file pdf_open_file($pdf, "philosophy.pdf");</li>
    <li> start a new page (A4) pdf_begin_page($pdf, 595, 842);</li>
    <li> get and use a font object $arial = pdf_findfont($pdf, "Arial", "host", 1); pdf_setfont($pdf, $arial, 10);</li>
    <li> print text pdf_show_xy($pdf, "There are more things in heaven and earth, Horatio,", 50, 750); pdf_show_xy($pdf, "than are dreamt of in your philosophy", 50, 730);</li>
    <li> end page pdf_end_page($pdf);</li>
    <li> close and save file pdf_close($pdf);</li>
    <li>?></li>
</ol>
&amp;nbsp;

PHP Benchmark Performance Script String Manipulation

This free PHP performance benchmark script is a free PHP script to calculate benchmark speeds  of PHP web hosting servers. The free PHP script performs some simple mathematics and string manipulating functions repetitively, and records the PHP code execution time it takes to complete the PHP functions. This benchmarking process is repeated the numbe

 

<?
/*
##########################################################################
#                   Free PHP Benchmark Performance Script                #
#                             Version 1.0.1                              #
#                        © 2006 Free-Webhosts.com                        #
##########################################################################
#
##########################################################################
#                                                                        #
#  Author      :  Free-Webhosts.com                                      #
#  Date        :  August 26, 2006                                        #
#  Website     :  http://www.free-webhosts.com/                          #
#  Details     :  http://www.free-webhosts.com/php-benchmark-script.php  #
#  Contact     :  http://www.free-webhosts.com/contact.php               #
#  License     :  FREE (GPL)                                             #
#                                                                        #
##########################################################################
#
# The free PHP script performs some simple math and string functions 20,000 times each, and measures how long it takes to complete the PHP execution. This is repeated the number of times given by the variable $iterations via a Javascript redirect to the script again, with 5 second delays.
# The average time is given, and also the average time after removing the highest and lowest completion times.
#
# It is recommended to host this script in a password-protected folder if possible; or otherwise to exclude it in robots.txt and rename it something more obscure.
#
# The script is used to compare the web server speeds of free PHP web hosting providers.
# The benchmark results (average PHP execution times of this script) for free PHP hosts are provided at:
#
# http://www.free-webhosts.com/php-hosting-comparison.php
#
*/


$iterations = 12;
if(isset($_SERVER['PHP_SELF'])) $PHP_SELF = $_SERVER['PHP_SELF'];
$starttime = explode(' ', microtime());
$string1 = 'abcdefghij';

for($i = 1; $i <= 20000; $i++)
{
$x=$i * 5;
$x=$x + $x;
$x=$x/10;
$string3 = $string1 . strrev($string1);
$string2 = substr($string1, 9, 1) . substr($string1, 0, 9);
$string1 = $string2;
}

$endtime = explode(' ', microtime());
$total_time = $endtime[0] + $endtime[1] - ($starttime[1] + $starttime[0]);
$total_time = round($total_time * 1000);

###################################################

if(isset($_GET['test'])) $test = $_GET['test'];
$test = (int)$test;
if(empty($test)) $test=0;

if(isset($_GET['ttimes']))
{
 $ttimes = $_GET['ttimes'];
 if($test>0 AND empty($ttimes)) { echo 'error'; die; }
 $itimes = explode('_', $ttimes);
 if(count($itimes)<$test)  { echo 'error 2'; die; }
}

$itimes[$test] = number_format($total_time,0);
$test_results = '';
$ttimes2 = '';
$TimesSum=0;

for($i = 0; $i <= $test; $i++)
{
 $itimes[$i] = (int)$itimes[$i];
 $TimesSum += $itimes[$i];
 $j=$i+1;
 $test_results .=  'Test #' . $j . ' completed in ' . $itimes[$i] . ' ms.<br>';
 $ttimes2 .= $itimes[$i];
 if($i < $test) $ttimes2 .= '_';
}

$test2 = $test+1;
$tquery = 'test=' . $test2 . '&amp;ttimes=' . $ttimes2;
$tquery2 = $tquery . '&amp;stop=1;';
$AverageAll = round($TimesSum/$test2);
$iterations2 = $iterations-1;
sort($itimes);
$lowest = $itimes[0];
$highest = $itimes[$test];
if(isset($_GET['stop'])) $stop = $_GET['stop'];
if(isset($stop)) $test = $iterations;

?>
<html><head>
<?
if($test<$iterations2) echo '<META HTTP-EQUIV="REFRESH" CONTENT="5; URL=' . $PHP_SELF . '?' . $tquery . '">';
?>
<title>Free PHP Benchmark Performance Script from Free-Webhosts.com</title>
<META name="ROBOTS" content="NOINDEX,NOFOLLOW">
<meta content="text/html; charset=windows-1252" http-equiv=content-type>
<meta http-equiv="Content-Style-Type" content="text/css">
</head>

<body>
<h1>Free PHP Benchmark Performance Script</h1>
<p><b><font face=Arial color="#999999" size=4>
<?

echo $test_results;
echo "<br>Lowest time: $lowest ms , Highest time : $highest ms<br>\n";
echo "Average of all $j times: <font size=\"+2\">$AverageAll ms</font><br>\n";
if($test2>2)
{
 $j-=2;
 $AverageMid = round(($TimesSum-$lowest-$highest)/$j);
 echo "Average of middle $j times: <font size=\"+2\">$AverageMid ms</font><br>\n";
}
echo '<br><a href="' . $PHP_SELF . '">Begin again</a>';
if($test<$iterations2) echo ' | <a href="' . $PHP_SELF . '?' . $tquery2 . '">Stop</a> | <font color=red>Doing ' . $iterations . ' iterations. Refreshing in 5 seconds...</font><br>';

?><br><br>
Copyright &amp;copy; 2006 , <a href="http://www.free-webhosts.com/" target="_top"><b>Free Web Hosting</a> (Free-Webhosts.com)<br></font></b>
</BODY></HTML>

Keywords from Text – PHP String Manipulation

I want to build my own tag cloud for an application I’m working on. The main tricky part would be pulling out ‘muli-word’ keywords such as “White House” and not recognising them as two separate words but one phrase.

 

<pre><code>function cs_get_tag_cloud_data($data)
{
    $data = str_replace(' ', '', $data);
    $tagwords_arr = explode(",", $data);
    $tags_arr = null;

    for( $x=0; $x<sizeof($tagwords_arr); $x++)
    {
        $word_count = get_tag_count($tagwords_arr, $tagwords_arr[$x]);

        if(in_tag_array($tags_arr, $tagwords_arr[$x]) == false)
        {
            $tags_arr[] = array("tag" => $tagwords_arr[$x], "count" => $word_count);
        }
    }

    return $tags_arr;      
}

# Get tag count
function get_tag_count($arr, $word)
{
    $wordCount = 0;
    for ( $i = 0; $i < sizeof($arr); $i++ )
    {
        if ( strtoupper($arr[$i]) == strtoupper($word) ) $wordCount++;
    }
    return $wordCount;
}

# check if word already exists
function in_tag_array($arr, $search)
{
    $tag_exists = false;
    if(sizeof($arr)>0)
    {
        for($b = 0; $b < sizeof($arr); $b++)
        {
            if (strtoupper($arr[$b]['tag']) == strtoupper($search))
            {
                $tag_exists = true;
                break;
            }
        }
    }
    else
    {
        $tag_exists = false;
    }
    return $tag_exists;
}
</code></pre>
&amp;nbsp;

String Manipulation Remove Tree And Files PHP

String manipulation forms the basis of many algorithms and utilities. Input validation, text analysis and file conversions are several direct applications of string manipulation. This tutorial explores some of the basics needed. Unless otherwise noted, the following classes are contained in the java.lang library.

 

<code> <?

function rmtree($dir,$s='*',$GLOB=NULL) {
 /** Dave Husk ,easyphpscripts.com
 recursive delete all files, and dirs if $s is *
 else delete files in search and will remove empty dirs if second pass
 */

 if(!is_dir($dir)) return(FALSE);
 foreach (glob($dir."/*",GLOB_ONLYDIR) as $sdir)
 if(@rmdir($sdir)) rmtree($dir,$s,$GLOB); else rmtree($sdir,$s,$GLOB);
 foreach (glob($dir."/$s",$GLOB) as $f){ @rmdir($f); @unlink($f); }
 return(TRUE);
}

?> </code>

&amp;nbsp;

PHP Javascript trim for String Manipulation

In programming, trim is a string manipulation function or algorithm. The most popular variants of the trim function strip only the beginning or end of the string. Typically named ltrim and rtrim respectively.This Javascript code trim implementation removes all leading and trailing occurrences of a set of characters specified. If no characters are specified it will trim whitespace characters from the beginning or end or both of the string.Without the second parameter, Javascript function will trim these characters.

 

<div>
<div>
<pre>/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/

 
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}</pre>
</div>
</div>
&amp;nbsp;

PHP Javascript sprintf Scripts string manipulation

Several programming languages implement a sprintf function, to output a formatted string. It originated from the C programming language, printf function. Its a string manipulation function. This script is a limited sprintf Javascript imple

 

 

<div>
<div>
<pre>/**
*
*  Javascript sprintf
*  http://www.webtoolkit.info/
*
*
**/

 
sprintfWrapper = {
 
    init : function () {
 
        if (typeof arguments == "undefined") { return null; }
        if (arguments.length &amp;lt; 1) { return null; }
        if (typeof arguments[0] != "string") { return null; }
        if (typeof RegExp == "undefined") { return null; }
 
        var string = arguments[0];
        var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
        var matches = new Array();
        var strings = new Array();
        var convCount = 0;
        var stringPosStart = 0;
        var stringPosEnd = 0;
        var matchPosEnd = 0;
        var newString = '';
        var match = null;
 
        while (match = exp.exec(string)) {
            if (match[9]) { convCount += 1; }
 
            stringPosStart = matchPosEnd;
            stringPosEnd = exp.lastIndex - match[0].length;
            strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
 
            matchPosEnd = exp.lastIndex;
            matches[matches.length] = {
                match: match[0],
                left: match[3] ? true : false,
                sign: match[4] || '',
                pad: match[5] || ' ',
                min: match[6] || 0,
                precision: match[8],
                code: match[9] || '%',
                negative: parseInt(arguments[convCount]) &amp;lt; 0 ? true : false,
                argument: String(arguments[convCount])
            };
        }
        strings[strings.length] = string.substring(matchPosEnd);
 
        if (matches.length == 0) { return string; }
        if ((arguments.length - 1) &amp;lt; convCount) { return null; }
 
        var code = null;
        var match = null;
        var i = null;
 
        for (i=0; i&amp;lt;matches.length; i++) {
 
            if (matches[i].code == '%') { substitution = '%' }
            else if (matches[i].code == 'b') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
                substitution = sprintfWrapper.convert(matches[i], true);
            }
            else if (matches[i].code == 'c') {
                matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
                substitution = sprintfWrapper.convert(matches[i], true);
            }
            else if (matches[i].code == 'd') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
                substitution = sprintfWrapper.convert(matches[i]);
            }
            else if (matches[i].code == 'f') {
                matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
                substitution = sprintfWrapper.convert(matches[i]);
            }
            else if (matches[i].code == 'o') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
                substitution = sprintfWrapper.convert(matches[i]);
            }
            else if (matches[i].code == 's') {
                matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
                substitution = sprintfWrapper.convert(matches[i], true);
            }
            else if (matches[i].code == 'x') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                substitution = sprintfWrapper.convert(matches[i]);
            }
            else if (matches[i].code == 'X') {
                matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
            }
            else {
                substitution = matches[i].match;
            }
 
            newString += strings[i];
            newString += substitution;
 
        }
        newString += strings[i];
 
        return newString;
 
    },
 
    convert : function(match, nosign){
        if (nosign) {
            match.sign = '';
        } else {
            match.sign = match.negative ? '-' : match.sign;
        }
        var l = match.min - match.argument.length + 1 - match.sign.length;
        var pad = new Array(l &amp;lt; 0 ? 0 : l).join(match.pad);
        if (!match.left) {
            if (match.pad == "0" || nosign) {
                return match.sign + pad + match.argument;
            } else {
                return pad + match.sign + match.argument;
            }
        } else {
            if (match.pad == "0" || nosign) {
                return match.sign + match.argument + pad.replace(/0/g, ' ');
            } else {
                return match.sign + match.argument + pad;
            }
        }
    }
}
 
sprintf = sprintfWrapper.init;</pre>
</div>
</div>
&amp;nbsp;