I have a series of tag in the text that I want to match with preg_match_all but the $regex string has something wrong and I can't understand what to do.
$tagReplace = ['mov', 'flv', 'youtube'];
foreach ($tagReplace as $plg_tag) {
$regex = "#{" . $plg_tag . "}(.*?){/" . $plg_tag . "}#s";
$var = preg_match_all($regex, "{mov}the_video_url{/mov}", $matches, PREG_PATTERN_ORDER);
var_dump($matches);
}
<?php
$matches = array();
$p = '/(mov|flv|youtube)/';
$replace_to = 'your text you want to be insted of the mov or flv or youtube';
$str = ' the string that you want to work on and replace its content';
$p_c = array(
$p => function($match) {
$ret = str_replace("mov", $replace_to, $match[0]);
$ret = str_replace("flv", $replace_to, $ret);
$ret = str_replace("youtube", $replace_to, $ret);
return $ret;
}
);
$res3 = preg_replace_callback_array($p_c, $str);
Related
I want the word between characters
'#' ,'_'
Change to
$word
Example :
#Ali_ is a good boy, I and #Jan_ love him
change to
Ali is a good boy, I and Jan love him
Thanks for your response
$string = 'ae #ali er #hassan sss';
$string = preg_replace("/#(.+?) /is", "<a href='Profile/$1'>$1</a>", $string);
echo($string);
Tried and tested:
function replaceString($content = '') {
preg_match_all('/#(.*?)_/', $content, $matches);
if(is_array($matches[0])) {
foreach($matches[0] as $key => $match) {
$new = $match;
$new = str_replace('#', '', $new);
$new = str_replace('_', '', $new);
$new = '' . $new . '';
$content = str_replace($match, $new, $content);
}
}
return $content;
}
The output of the following:
$content = '#name1_ and this other #name2_';
$content = replaceString($content);
echo $content;
Will be:
name1 and this other name2
How can I process text with some codes.
So suppose I have text as below
Hello {::first_name::} {::last_name::},
How are you?
Your organisation is {::organisation::}
For any text between {:: and ::} should be evaluated to get its value.
I tried exploding text to array using space as delimiter and then parsing array items to look for "{::" and if found get string between "{::" and "::}" and calling database to get this field value.
So basically these will be db fields.
Below is the code I have tried
$msg = "Hello {::first_name::} {::last_name::},
How are you?
Your organisation is {::organisation::}";
$msg_array = explode(" ", $msg);
foreach ($msg_array as $str) {
if (strpos($str, "{::") !== false) {
$field_str = get_string_between($str, "{::", "::}");
$field_value = $bean->$field_str; //Logic that gets the value of the field
$msgStr .= $field_value . " ";
} else {
$msgStr .= $str . " ";
}
}
function get_string_between($string, $start, $end)
{
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
Your script seems fine. Your script in fiddle
If you are looking for alternative way, you can try using preg_match_all() with str_replace(array, array, source)
<?php
$bean = new stdClass();
$bean->first_name = 'John';
$bean->last_name = 'Doe';
$bean->organisation = 'PHP Company';
$string = "Hello {::first_name::} {::last_name::}, How are you? Your organisation is {::organisation::}";
// find all placeholders
preg_match_all('/{::(.+?)::}/i', $string, $matches);
$placeholders = $matches[0];
//strings inside placeholders
$parts = $matches[1];
// return values from $bean by matching object property with strings inside placeholders
$replacements = array_map(function($value) use ($bean) {
// use trim() to remove unexpected space
return $bean->{trim($value)};
}, $parts);
echo $newstring = str_replace($placeholders, $replacements, $string);
Short format:
$string = "Hello {::first_name::} {::last_name::}, How are you? Your organisation is {::organisation::}";
preg_match_all('/{::(.+?)::}/i', $string, $matches);
$replacements = array_map(function($value) use ($bean) {
return $bean->{trim($value)};
}, $matches[1]);
echo str_replace($matches[0], $replacements, $string);
And if you prefer to use a function:
function holder_replace($string, $source = null) {
if (is_object($source)) {
preg_match_all('/{::(.+?)::}/i', $string, $matches);
$replacements = array_map(function($value) use ($source) {
return (property_exists(trim($value), 'source')) ? $source->{trim($value)} : $value;
}, $matches[1]);
return str_replace($matches[0], $replacements, $string);
}
return $string;
};
echo holder_replace($string, $bean);
OUTPUT:
Hello John Doe, How are you? Your organisation is PHP Company
fiddle
Or you can simply use str_replace function:
$data = "{:: string ::}";
echo str_replace("::}", "",str_replace("{::", "", $data));
I have a question, if anyone can help me to solve this. I have a string separated by commas, and I want to find an item that partially matches:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
I need to get only the full string from partial match as a result of filter:
$result = "GenomaPrintOrder";
With preg_match_all you can do like this.
Php Code
<?php
$subject = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView, NewPrintOrder";
$pattern = '/\b([^,]*PrintOrder[^,]*)\b/';
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "Matched: " . $val[1]. "\n";
}
?>
Output
Matched: GenomaPrintOrder
Matched: NewPrintOrder
Ideone Demo
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$result = array();
$tmp = explode(",", $string);
foreach($tmp as $entrie){
if(strpos($entrie, $string) !== false)
$result[] = trim($entrie);
}
This will get you an array with all strings that match your search-string.
You can use regular expression to get the result:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$regex = '/([^,]*' . preg_quote($search, '/') . '[^,]*)/';
preg_match($regex, $string, $match);
$result = trim($match[1]); // $result == 'GenomaPrintOrder'
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$array = explode(" ", $string);
echo array_filter($array, function($var) use ($search) { return preg_match("/\b$searchword\b/i", $var); });
Since there are so many different answers already, here is another:
$result = preg_grep("/$search/", explode(", ", $string));
print_r($result);
I used the function str_word_count to count how many ARABIC words are in a text, but it returns zero:
$sentence = 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ';
$countSentence = str_word_count($sentence);
echo 'Total words '.$countSentence.'<br />';
Thanks in advance
Try to use this function
if (!function_exists('utf8_str_word_count')){
function utf8_str_word_count($string, $format = 0, $charlist = null) {
if ($charlist === null) {
$regex = '/\\pL[\\pL\\p{Mn}\'-]*/u';
}
else {
$split = array_map('preg_quote',
preg_split('//u',$charlist,-1,PREG_SPLIT_NO_EMPTY));
$regex = sprintf('/(\\pL|%1$s)([\\pL\\p{Mn}\'-]|%1$s)*/u',
implode('|', $split));
}
switch ($format) {
default:
case 0:
// For PHP >= 5.4.0 this is fine:
return preg_match_all($regex, $string);
// For PHP < 5.4 it's necessary to do this:
// $results = null;
// return preg_match_all($regex, $string, $results);
case 1:
$results = null;
preg_match_all($regex, $string, $results);
return $results[0];
case 2:
$results = null;
preg_match_all($regex, $string, $results, PREG_OFFSET_CAPTURE);
return empty($results[0])
? array()
: array_combine(
array_map('end', $results[0]),
array_map('reset', $results[0]));
}
}
}
Example
$sentence = 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ';
$countSentence = utf8_str_word_count($sentence);
echo 'Total words '.$countSentence.'<br />';
I want to filter the input text if it's got A URL inside it.
By URL I mean that every thing that corresponds to a valid internet address like www.example.com, example.com, http://www.example.com, http://example.com/foo/bar.
I think I've gotta use regular expressions and the preg_match function so I need the correct regexp pattern for this purpose.
I'd be very grateful if anybody could give me that.
This article has a nice regex for matching urls: http://daringfireball.net/2010/07/improved_regex_for_matching_urls
For PHP you would need to escape the regex properly, for example like this:
$text = "here is some text that contains a link to www.example.com, and it will be matched.";
preg_match("/(?i)\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/", $text, $matches);
var_dump($matches);
$html = "http://www.scroogle.org
http://www.scroogle.org/
http://www.scroogle.org/index.html
http://www.scroogle.org/index.html?source=library
You can surf the internet anonymously at https://ssl.scroogle.org/cgi-bin/nbbwssl.cgi.";
preg_match_all('/\b((?P<protocol>https?|ftp):\/\/(?P<domain>[-A-Z0-9.]+)(?P<file>\/[-A-Z0-9+&##\/%=~_|!:,.;]*)?(?P<parameters>\?[A-Z0-9+&##\/%=~_|!:,.;]*)?)/i', $html, $urls, PREG_PATTERN_ORDER);
$urls = $urls[1][0];
Will match:
http://www.scroogle.org
http://www.scroogle.org/
http://www.scroogle.org/index.html
http://www.scroogle.org/index.html?source=library
You can surf the internet anonymously at https://ssl.scroogle.org/cgi-bin/nbbwssl.cgi.
To loop results you can use:
for ($i = 0; $i < count($urls[0]); $i++) {
echo $urls[1][$i]."\n";
}
will output:
http://www.scroogle.org
http://www.scroogle.org/
http://www.scroogle.org/index.html
http://www.scroogle.org/index.html?source=library
https://ssl.scroogle.org/cgi-bin/nbbwssl.cgi
cheers, Lob
Found here: http://zenverse.net/php-function-to-auto-convert-url-into-hyperlink/
Functions from WordPress.
function _make_url_clickable_cb($matches) {
$ret = '';
$url = $matches[2];
if ( empty($url) )
return $matches[0];
// removed trailing [.,;:] from URL
if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
}
return $matches[1] . "$url" . $ret;
}
function _make_web_ftp_clickable_cb($matches) {
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;
if ( empty($dest) )
return $matches[0];
// removed trailing [,;:] from URL
if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
return $matches[1] . "$dest" . $ret;
}
function _make_email_clickable_cb($matches) {
$email = $matches[2] . '#' . $matches[3];
return $matches[1] . "$email";
}
function make_clickable($ret) {
$ret = ' ' . $ret;
// in testing, using arrays here was found to be faster
$ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?#\[\]+]*)#is', '_make_url_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?#\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)#(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
// this one is not in an array because we need it to run last, for cleanup of accidental links within links
$ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
$ret = trim($ret);
return $ret;
}
Usage:
$string = 'I have some texts here and also links such as http://www.youtube.com , www.haha.com and lol#example.com. They are ready to be replaced.';
echo make_clickable($string);