IT Community - Software Programming, Web Development and Technical Support

string functions and manipulations in php

This is a discussion on string functions and manipulations in php within the PHP Programming forums, part of the Web Development category; Hi Venkat charya, In some cases i need to find the number occurrence of a string in a text file. ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > PHP Programming

Register FAQ Members List Calendar Mark Forums Read
  #41 (permalink)  
Old 10-26-2007, 12:31 AM
Anand Anand is offline
D-Web Programmer
 
Join Date: Mar 2007
Posts: 52
Anand is on a distinguished road
Default Re: string functions and manipulations in php

Hi Venkat charya,

In some cases i need to find the number occurrence of a string in a text file. Is there any shorter way to the no. of occurrences using the string functions available in php. Or i need to loop through the text completely and iterate the counts.
__________________
None of us is As Strong as All of us.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #42 (permalink)  
Old 10-28-2007, 11:02 PM
vims vims is offline
D-Web Programmer
 
Join Date: Oct 2007
Posts: 67
vims is on a distinguished road
Wink Re: string functions and manipulations in php

Quote:
Originally Posted by Anand View Post
Hi,

I have one basic doubt. How can we show the PHP codes and HTML tags to show up in a browser, like the one which we show in the DiscussWeb forum. I would like to read a php page and show all the contents in the browser.

You can do it by browse the php file that you want to see the content and read the file contents and display the file in the textaread

Let us see the below example

<? if($_FILES["flePage"]["tmp_name"] != "")
{

$vFname = $_FILES["flePage"]["name"];
$vFopen = fopen($vFname,'r');
$vContent = fread($vFopen,filesize($vFname));
fclose($vFopen);
}
?>


<form method="post" name="frm1" action="" enctype="multipart/form-data" onSubmit="">
<input name="flePage" type="file">
<br><br>
<textarea name="txtarea" rows="10" cols="70"><?= stripslashes($vContent); ?></textarea>
<input type="submit" name="validate" onClick="funValidate();">
</form>

<script>
function funValidate()
{
document.frm1.submit();
}
</script>


Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #43 (permalink)  
Old 10-28-2007, 11:18 PM
vims vims is offline
D-Web Programmer
 
Join Date: Oct 2007
Posts: 67
vims is on a distinguished road
Wink Re: string functions and manipulations in php

Quote:
Originally Posted by Anand View Post
Hi Venkat charya,

In some cases i need to find the number occurrence of a string in a text file. Is there any shorter way to the no. of occurrences using the string functions available in php. Or i need to loop through the text completely and iterate the counts.
Hi Anand,
You can find the number of occurence of a string in a text file through the string function called substr_count. To implement this, you have to read the text file content and use the substr_count function to find the number of occurence of string


$vFname = "filename.txt";
$vFopen = fopen($vFname,'r');
$vContent = fread($vFopen,filesize($vFname));
$vSubString = substr_count($vContent, "search string");
echo "No. of Occurence of string===". $vSubString;
fclose($vFopen);


Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #44 (permalink)  
Old 10-28-2007, 11:22 PM
vims vims is offline
D-Web Programmer
 
Join Date: Oct 2007
Posts: 67
vims is on a distinguished road
Wink Re: string functions and manipulations in php

Hi...

Can anybody explain about the regular expression in php with example?
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #45 (permalink)  
Old 10-30-2007, 05:43 AM
Senthilkumar Senthilkumar is offline
D-Web Programmer
 
Join Date: Mar 2007
Posts: 93
Senthilkumar is on a distinguished road
Default Re: string functions and manipulations in php

Hi

Two types of regular experssions available in PHP

1.Regular Expression Functions (POSIX Extended)
2.Regular Expression Functions (Perl-Compatible)

Thanks
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #46 (permalink)  
Old 10-30-2007, 07:53 AM
venkat_charya venkat_charya is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 118
venkat_charya is on a distinguished road
Thumbs up Re: string functions and manipulations in php

Here is small description about these two regular expression. [POSIX Extended and Perl-Compatible]

POSIX or "Portable Operating System Interface for uniX" is a collection of standards that define some of the functionality that a (UNIX) operating system should support. One of these standards defines two flavors of regular expressions. Commands involving regular expressions, such as grep and egrep, implement these flavors on POSIX-compliant UNIX systems.

While in Perl Compatible, the syntax for patterns used in these functions closely resembles Perl. The expression should be enclosed in the delimiters, a forward slash (/), for example. Any character can be used for delimiter as long as it's not alphanumeric or backslash (\). If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style (), {}, [], and <> matching delimiters.

Thanks
__________________
K K Venkata Charya
Success is easy to get but difficult to retain
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #47 (permalink)  
Old 10-31-2007, 02:56 AM
Anand Anand is offline
D-Web Programmer
 
Join Date: Mar 2007
Posts: 52
Anand is on a distinguished road
Default Re: string functions and manipulations in php

Hi senthilkumar,

Can you give some examples on these. so that it would be helpful in understanding better on the regular expressions.
__________________
None of us is As Strong as All of us.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #48 (permalink)  
Old 10-31-2007, 04:23 AM
Senthilkumar Senthilkumar is offline
D-Web Programmer
 
Join Date: Mar 2007
Posts: 93
Senthilkumar is on a distinguished road
Default Re: string functions and manipulations in php

Hi
i have explain in detail about Regular Expression Functions (Perl-Compatible)


1 Pattern Modifiers

Pattern Modifiers -- Describes possible modifiers in regex patterns

Description
The current possible PCRE modifiers are listed below. The names in parentheses refer to internal PCRE names for these modifiers. Spaces and newlines are ignored in modifiers, other characters cause error.


  • i (PCRE_CASELESS)

    If this modifier is set, letters in the pattern match both upper and lower case letters.

  • m (PCRE_MULTILINE)

    By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl.

    When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.

  • s (PCRE_DOTALL)

    If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

  • x (PCRE_EXTENDED)

    If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.

  • e

    If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single and double quotes are escaped by backslashes in substituted backreferences.

    Only preg_replace() uses this modifier; it is ignored by other PCRE functions.

    ????: This modifier was not available in PHP 3.


  • A (PCRE_ANCHORED)

    If this modifier is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.

  • D (PCRE_DOLLAR_ENDONLY)

    If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl.

  • S

    When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character.

  • U (PCRE_UNGREEDY)

    This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).

  • X (PCRE_EXTRA)

    This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this modifier.

  • u (PCRE_UTF8)

    This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern strings are treated as UTF-8. This modifier is available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32. UTF-8 validity of the pattern is checked since PHP 4.3.5.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #49 (permalink)  
Old 11-01-2007, 12:57 AM
venkat_charya venkat_charya is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 118
venkat_charya is on a distinguished road
Thumbs up Re: string functions and manipulations in php

Hi,

Here is some explaination about POSIX [Portable Operating System Interface for uniX] regular expression.

Regular expressions are used for complex string manipulation. PHP uses the POSIX extended regular expressions as defined by POSIX 1003.2.It is similar in syntax to the traditional Unix regular expressions, with some exceptions. The following metacharacters are added:

? Matches the preceding element zero or one time. For example, ba? matches "b" or "ba".
+ Matches the preceding element one or more times. For example, ba+ matches "ba", "baa", "baaa", and so on.
| The choice (aka alternation or set union) operator matches either the expression before or the expression after the operator. For example, abc|def matches "abc" or "def".


Additionally, some backslashes are removed: \{...\} becomes {...}, and \(...\) becomes (...).

Examples:

[hc]+at matches "hat", "cat", "hhat", "chat", "hcat", "ccchat", and so on, but not "at".
[hc]?at matches "hat", "cat", and "at".
cat|dog matches "cat" or "dog".
Since the characters (, ), [, ], ., *, ?, +, ^, |, and $ are used as special symbols, they have to be escaped if they are meant literally. This is done by preceding them with \, which therefore also has to be escaped this way if meant literally.


Extended POSIX regular expressions can often be used with modern Unix utilities by including the command line flag -E.

Examples:
<?php
// Returns true if "abc" is found at the beginning of $string.
ereg("^abc", $string);

// Returns true if "abc" is found at the end of $string.
ereg("abc$", $string);

// Returns true if client browser is Netscape 2, 3 or MSIE 3.
eregi("(ozilla.[23]|MSIE.3)", $HTTP_USER_AGENT);

// Put a <br /> tag at the end of $string.
$string = ereg_replace("$", "<br />", $string);
?>


Thanks
__________________
K K Venkata Charya
Success is easy to get but difficult to retain
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #50 (permalink)  
Old 11-01-2007, 07:29 AM
Senthilkumar Senthilkumar is offline
D-Web Programmer
 
Join Date: Mar 2007
Posts: 93
Senthilkumar is on a distinguished road
Default Re: string functions and manipulations in php

preg_grep

Description

array preg_grep ( string pattern, array input [, int flags] )

preg_grep, is used to search an array for specific patterns and then return a new array based on that filtering. There are two ways to return the results. You can return them as is, or you can invert them (instead of only returning what matches, it would only return what does not match.)

flags can be the following flag:

PREG_GREP_INVERT
If this flag is passed, preg_grep() returns the elements of the input array that do not match the given pattern. This flag is available since PHP 4.2.0.


1. preg_grep() example

$data = array(0, 1, 2, 'three', 4, 5, 'six', 7, 8, 'nine', 10);
$mod1 = preg_grep("/4|5|6/", $data);
$mod2 = preg_grep("/[0-9]/", $data, PREG_GREP_INVERT);
print_r($mod1);
echo "<br>";
print_r($mod2);

This code would result in the following data:
Array ( [4] => 4 [5] => 5 )
Array ( [3] => three [6] => six [9] => nine )

First we assign our $data variable. This is a list of numbers, some in alpha form, others in numeric. The first thing we run is called $mod1. Here we are searching for anything that contains 4, 5, or 6. When our result is printed below we only get 4 and 5, because 6 was written as 'six' so it did not match our search.

Next we run $mod2, which is searching for anything that contains a numeric character. But this time we include PREG_GREP_INVERT. This will invert our data, so instead of outputting numbers, it outputs all of our entries that where not numeric (three, six and nine).
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #51 (permalink)  
Old 11-01-2007, 07:43 AM
Senthilkumar Senthilkumar is offline
D-Web Programmer
 
Join Date: Mar 2007
Posts: 93
Senthilkumar is on a distinguished road
Default Re: string functions and manipulations in php

preg_match

Preg_Match function is used to search a string, and return a 1 or 0. If the search was successful a 1 will be returned, and if it was not found a 0 will be returned.

Description

int preg_match ( string pattern, string subject [, array &matches [, int flags [, int offset]]] )


Searches subject for a match to the regular expression given in pattern.

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

flags can be the following flag:


PREG_OFFSET_CAPTURE
If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1. This flag is available since PHP 4.3.0 .

Example

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

will produce

Array
(
[0] => Array
(
[0] => def
[1] => 0
)

)

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #52 (permalink)  
Old 11-02-2007, 07:38 AM
venkat_charya venkat_charya is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 118
venkat_charya is on a distinguished road
Thumbs up Re: string functions and manipulations in php

Hi

Here is some information about ereg_replace regular expression.

ereg_replace -- Replace regular expression

Description
string ereg_replace ( string pattern, string replacement, string string )

This function scans string for matches to pattern, then replaces the matched text with replacement.

The modified string is returned. (Which may mean that the original string is returned if there are no matches to be replaced.)

If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

If no matches are found in string, then string will be returned unchanged.

<?php

$string = "This is a test";
echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "\\1was", $string);
echo ereg_replace("(( )is)", "\\2was", $string);

?>


Thanks
__________________
K K Venkata Charya
Success is easy to get but difficult to retain
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #53 (permalink)  
Old 11-05-2007, 12:48 AM
venkat_charya venkat_charya is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 118
venkat_charya is on a distinguished road
Thumbs up Re: string functions and manipulations in php

Hi,

Here i am discussing about preg_replace() function.

preg_replace -- Perform a regular expression search and replace Description

Systax
mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])

Description
Searches subject for matches to pattern and replaces them with replacement. If limit is specified, then only limit matches will be replaced; if limit is omitted or is -1, then all matches are replaced.

Replacement may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

Every parameter to preg_replace() can be an array.

If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.

If pattern and replacement are arrays, then preg_replace() takes a value from each array and uses them to do search and replace on subject. If replacement has fewer values than pattern, then empty string is used for the rest of replacement values. If pattern is an array and replacement is a string; then this replacement string is used for every value of pattern. The converse would not make sense, though.

/e modifier makes preg_replace() treat the replacement parameter as PHP code after the appropriate references substitution is done. Tip: make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().


Example Code
$patterns = array ("/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/",
"/^\s*{(\w+)}\s*=/");
$replace = array ("\\3/\\4/\\1\\2", "$\\1 =");
print preg_replace ($patterns, $replace, "{startDate} = 1999-5-27");


Output
This example will produce: $startDate = 5/27/1999

Thanks
__________________
K K Venkata Charya
Success is easy to get but difficult to retain
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #54 (permalink)  
Old 11-08-2007, 04:39 AM
Gopisoft Gopisoft is offline
D-Web Sr.Programmer
 
Join Date: Feb 2007
Posts: 117
Gopisoft is on a distinguished road
Default Re: string functions and manipulations in php

Hi,

strtr() vs str_replace()

PHP Code:
<PHP
$src_str 
file_get_contents("big_content_file_path");
$src = array('abc'123'text');
$dst = array('cba'321'txet');
$s microtime(1);
for (
$i 0$i 10000$i++)
str_replace($src$dst$src_str);
$e microtime(1);
echo (
$e $s) . "\n"// 5.69 seconds

//-----------------------------------------
$new_rep array_combine($src$dst);
$s microtime(1);
for (
$i 0$i 10000$i++)
strtr($src_str$new_rep);
$e microtime(1);
echo (
$e $s) . "\n"// 54.42 seconds
?> 
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #55 (permalink)  
Old 11-08-2007, 09:54 PM
venkat_charya venkat_charya is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 118
venkat_charya is on a distinguished road
Thumbs up Re: string functions and manipulations in php

Hi,

strripos() vs strrpos()

strripos -- Find position of last occurrence of a case-insensitive string in a string
strrpos -- Find position of last occurrence of a char in a string

PHP Code:
<?php
/*-----------STRRIPOS------------------------*/
$haystack 'ababcd';
$needle   'aB';

$pos      strripos($haystack$needle);

if (
$pos === false) {
    echo 
"Sorry, we did not find ($needle) in ($haystack)";
} else {
    echo 
"Congratulations!\n";
    echo 
"We found the last ($needle) in ($haystack) at position ($pos)";
}
/*-------------------------------------------*/
/*-----------STRRPOS------------------------*/
// in PHP 4.0b3 and newer:
$pos strrpos($mystring"b");
if (
$pos === false) { // note: three equal signs
    // not found...
}

// in versions older than 4.0b3:
$pos strrpos($mystring"b");
if (
is_bool($pos) && !$pos) {
    
// not found...
}
/*-------------------------------------------*/
?>
Thanks
__________________
K K Venkata Charya
Success is easy to get but difficult to retain
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #56 (permalink)  
Old 11-08-2007, 10:29 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: string functions and manipulations in php

What is the difference of using explode and split in PHP?
I know that both are converting a string into array
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #57 (permalink)  
Old 11-09-2007, 01:00 AM
venkat_charya venkat_charya is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 118
venkat_charya is on a distinguished road
Thumbs up Re: string functions and manipulations in php

Quote:
Originally Posted by Jeyaseelansarc View Post
What is the difference of using explode and split in PHP?
I know that both are converting a string into array
Hi Jeyaseelansarc,

Yes, both are used to convert a string into array. But there is one major difference what i know is regular expression usage.

explode is used string by string while Split is used to split string into array by regular expression.

In search pattern we can use regular expression while using split but we can not able to do the same in explode.

Thanks
__________________
K K Venkata Charya
Success is easy to get but difficult to retain
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #58 (permalink)  
Old 11-09-2007, 01:54 AM
Anand Anand is offline
D-Web Programmer
 
Join Date: Mar 2007
Posts: 52
Anand is on a distinguished road
Default Re: string functions and manipulations in php

Hi venkatcharya,

Can you please provide the scenarios under what circumstances we need to use the explode and split functions in PHP. Which one is better in considering the performance.
__________________
None of us is As Strong as All of us.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #59 (permalink)  
Old 11-09-2007, 05:34 AM