I need search and highlight the word.
My sentence is
Please see our Author Guide for more information: http://digital-library.theiet.org/journals/author-guide.
you will be contacted shortly asking you to take a decision and sign either a copyright or Open Access licence form.
My code
function find_highlight_word($word) {
$text = preg_replace_callback($word, function($matches) use (&$counter) {
$counter++;
return '<b class="search_mark highlighted" id="matched_' . $counter . '">'
. substr($matches[0], 0, strlen($matches[0]))
. '</b>';
}, $text);
return $text;
}
$word = '//';
$word = '/' . preg_quote($word) . '/i';
$this->find_highlight_word($word);
When I'm searching with '//' that time showing php error.
You're correctly attempting to preg-quote your string, but you're not telling it what your delimiter is, so the // inside the string is causing issues. Pass the used delimiter as the second argument, so it can be escaped as well:
$word = '/' . preg_quote($string, '/') . '/i';
I want to set a variable to an HTML image tag with a variable source. Here is my function.
function convertImageMod($string)
{
$string = preg_replace('/\s+/', '', $string);
$string = str_replace("'", "", $string);
$stringlength = strlen($string);
$stringlength -= 3;
$string = substr ($string, 0, $stringlength);
$string = strtolower ($string);
$string = "<img src:\"images/items/" . "$string" . ".png" . "\"></img>" ";
return $string;
}
However, I keep getting the following error:
Parse error: syntax error, unexpected '"' in C:\web\functions.php on line 26
I thought I had properly escaped all of the necessary quotes.
Any idea what I'm getting this error message?
Typo there:
$string = "<img src:\"images/items/" . "$string" . ".png" . "\"></img>" ";
You may fix with this:
$string = "<img src=\"images/items/{$string}.png\">";
You are not properly escaped " double quotes.
UPD:
Also, <img /> tag does not require a closing tag. See specifications.
Why dont use "double quotes" for the variable and inside 'simple quotes', it's much clean and easy to read
$string = "<img src='images/items/{$string}.png'>";
As the error message says you have a " too many in the line:
$string = "<img src:\"images/items/" . "$string" . ".png" . "\"></img>" ";
It should read:
$string = "<img src:\"images/items/" . "$string" . ".png" . "\"></img>";
Change:
Line 26
$string = "<img src:\"images/items/" . "$string" . ".png" . "\"></img>" ";
To:
Line 26:
$string = "<img src:\"images/items/".$string.".png \"></img>";
I've made some progress with my regex that I'm using to extract attributes from pseudo-xml-tags, but then I got ambitous and wanted to correctly handle quoted attributes (with quotes being optional):
regex
~\{language\s*=\s*(P?<quote>[\"\']*)(?P<att>.*?)(?P=quote)\s*/\}~
(this is the output of the var that is used as arg in preg_match, so 'sensible things' such as \" were created with chr(92) . chr(34) beforehand...)
input
kjkjkjkjkjkj{language= 'DE' /}xxxxlxlxlxlllllk
extracts 'DE' when testing with RegexBuddy. But PHPs preg_match issues a warning: Warning: preg_match(): Compilation failed: reference to non-existent subpattern at offset 56.
What's the problem? I thought "quote" was assigned before...
Here's the complete program, just in case I have a PHP-error somewhere:
<?php
$QQ=chr(92) . chr(34);
$delimeters = "{}";
$del0 = preg_quote($delimeters{0});
$del1 = preg_quote($delimeters{1});
$tag="language";
$string="fdfdfdfdf{language=1}testhgg";
$preg1 = "|" . $del0 . $tag . "[^" . $del1 . "]*" . $del1 . "(.*?)" . $del0 . "/" . $tag . $del1 . "|";
$preg2 = "~" . $del0 . $tag . "\s*=\s*(?P<" . "quote>[" . $QQ . "\']*)(?P<att>.*?)(?P=quote)\s*/" . $del1 . "~";
$match=array();
preg_match($preg1,$string,$match);
echo "<br>match1:<pre>";var_dump($match);echo"</pre>";
$match=array();
preg_match($preg2,$string,$match);
echo "<br>match2:<pre>";var_dump($match);echo"</pre>";
?>
Your named subpattern is formatted incorrectly.
(P?<quote>[\"\']*)
should be
(?P<quote>[\"\']*)
See http://php.net/manual/en/regexp.reference.subpatterns.php
Background: Working with MediaWiki 1.19.1, Graphviz 2.28.0, Extension:GraphViz 0.9 on WAMP stack (Server 2008, Apache 2.4.2, MySQL 5.5.27, PHP 5.4.5). Everything is working great and as expected for the basic functionality of rendering a clickable image from a Graphviz diagram using the GraphViz extension in MediaWiki.
Problem: The links in the image map are not added to the MediaWiki pagelinks table. I get why they aren't added but it becomes an issue if there is no way to follow the links back with the 'What links here' functionality.
Desired solution: During the processing of the diagram in the GraphViz extension, I would like to use the generated .map file to then create a list of wikilinks to add on the page to get picked up by MediaWiki and added to the pagelinks table.
Details:
This GraphViz extension code:
<graphviz border='frame' format='png'>
digraph example1 {
// define nodes
nodeHello [
label="I say Hello",
URL="Hello"
]
nodeWorld [
label="You say World!",
URL="World"
]
// link nodes
nodeHello -> nodeWorld!
}
</graphviz>
Generates this image:
And this image map code in a corresponding .map file on the server:
<map id="example1" name="example1">
<area shape="poly" id="node1" href="Hello" title="I say Hello" alt="" coords="164,29,161,22,151,15,137,10,118,7,97,5,77,7,58,10,43,15,34,22,31,29,34,37,43,43,58,49,77,52,97,53,118,52,137,49,151,43,161,37"/>
<area shape="poly" id="node2" href="World" title="You say World!" alt="" coords="190,125,186,118,172,111,152,106,126,103,97,101,69,103,43,106,22,111,9,118,5,125,9,133,22,139,43,145,69,148,97,149,126,148,152,145,172,139,186,133"/>
</map>
From that image map file, I would like to be able to extract the href and title to build wikilinks like so:
[[Hello|I say Hello]]
[[World|You say World!]]
I'm guessing that since that .map file is essentially XML that I could just use XPATH to query the file, but that is just a guess. PHP is not my strongest area and I don't know the best approach to going about the XML/XPATH option or if that is even the best approach to pull that info from the file.
Once I got that collection/array of wikilinks from the .map file, I'm sure I can hack up the GraphViz.php extension file to add it to the contents of the page to get it added to the pagelinks table.
Progress: I had a bit of an Rubber Duck Problem Solving moment right as I submitted the question. I realized that since I had well formed data in the image map, that XPATH was probably the way to go. It was fairly trivial to be able to pull the data I needed, especially since I found that the map file contents was stilled stored in a local string variable.
$xml = new SimpleXMLElement( $map );
foreach($xml->area as $item) {
$links .= "[[" . $item->attributes()->href . "|" . $item->attributes()->title . "]]";
}
Final Solution: See my accepted answer below.
Thanks for taking a look. I appreciate any assistance or direction you can offer.
I finally worked through all of the issues and now have a fairly decent solution to render the graph nicely, provide a list of links, and register the links with wiki. My solution doesn't fully support all of the capabilities of the current GraphViz extension as it is written as there is functionality we do not need and I do not want to support. Here are the assumptions / limitations of this solution:
Does not support MscGen: We only have a need for Graphviz.
Does not support imageAtrributes: We wanted to control the format and presentation and it seemed like there were inconsistencies in the imageAttributes implementation that would then cause further support issues.
Does not support wikilinks: While it would be nice to provide consistent link usage through wiki and the Graphviz extension, the reality is that Graphviz is a completely different markup environment. While the current extension 'supports' wikilinks, the implementation is a little weak and leaves areas for confusion. Example: Wikilinks support giving the link an optional description but Graphviz already uses the node label for the description. So then you end up ignoring the wikilink description and telling users that 'Yes, we support wikilinks but don't use the description part' So since we aren't really using wikilinks correctly, just implement a regular link implementation and try to avoid the confusion entirely.
Here is what the output looks like:
Here are the changes that were made
Comment out this line:
// We don't want to support wikilinks so don't replace them
//$timelinesrc = rewriteWikiUrls( $timelinesrc ); // if we use wiki-links we transform them to real urls
Replace this block of code:
// clean up map-name
$map = preg_replace( '#<ma(.*)>#', ' ', $map );
$map = str_replace( '</map>', '', $map );
if ( $renderer == 'mscgen' ) {
$mapbefore = $map;
$map = preg_replace( '/(\w+)\s([_:%#/\w]+)\s(\d+,\d+)\s(\d+,\d+)/',
'<area shape="$1" href="$2" title="$2" alt="$2" coords="$3,$4" />',
$map );
}
/* Procduce html
*/
if ( $wgGraphVizSettings->imageFormatting )
{
$txt = imageAtrributes( $args, $storagename, $map, $outputType, $wgUploadPath ); // if we want borders/position/...
} else {
$txt = '<map name="' . $storagename . '">' . $map . '</map>' .
'<img src="' . $wgUploadPath . '/graphviz/' . $storagename . '.' . $outputType . '"' .
' usemap="#' . $storagename . '" />';
}
With this code:
$intHtml = '';
$extHtml = '';
$badHtml = '';
// Wrap the map/area info with top level nodes and load into xml object
$xmlObj = new SimpleXMLElement( $map );
// What does map look like before we start working with it?
wfDebugLog( 'graphviz', 'map before: ' . $map . "\n" );
// loop through each of the <area> nodes
foreach($xmlObj->area as $areaNode) {
wfDebugLog( 'graphviz', "areaNode: " . $areaNode->asXML() . "\n" );
// Get the data from the XML attributes
$hrefValue = (string)$areaNode->attributes()->href;
$textValue = (string)$areaNode->attributes()->title;
wfDebugLog( 'graphviz', '$hrefValue before: ' . $hrefValue . "\n" );
wfDebugLog( 'graphviz', '$textValue before: ' . $textValue . "\n" );
// For the text fields, multiple spaces (" ") in the Graphviz source (label)
// turns into a regular space followed by encoded representations of
// non-breaking spaces (" ") in the .map file which then turns
// into the following in the local variables: (" Â Â ").
// The following two options appear to convert/decode the characters
// appropriately. Leaving the lines commented out for now, as we have
// not seen a graph in the wild with multiple spaces in the label -
// just happened to stumble on the scenario.
// See http://www.php.net/manual/en/simplexmlelement.asxml.php
// and http://stackoverflow.com/questions/2050723/how-can-i-preg-replace-special-character-like-pret-a-porter
//$textValue = iconv("UTF-8", "ASCII//TRANSLIT", $textValue);
//$textValue = html_entity_decode($textValue, ENT_NOQUOTES, 'UTF-8');
// Now we need to deal with the whitespace characters like tabs and newlines
// and also deal with them correctly to replace multiple occurences.
// Unfortunately, the \n and \t values in the variable aren't actually
// tab or newline characters but literal characters '\' + 't' or '\' + 'n'.
// So the normally recommended regex '/\s+/u' to replace the whitespace
// characters does not work.
// See http://stackoverflow.com/questions/6579636/preg-replace-n-in-string
$hrefValue = preg_replace("/( |\\\\n|\\\\t)+/", ' ', $hrefValue);
$textValue = preg_replace("/( |\\\\n|\\\\t)+/", ' ', $textValue);
// check to see if the url matches any of the
// allowed protocols for external links
if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $hrefValue ) ) {
// external link
$parser->mOutput->addExternalLink( $hrefValue );
$extHtml .= Linker::makeExternalLink( $hrefValue, $textValue ) . ', ';
}
else {
$first = substr( $hrefValue, 0, 1 );
if ( $first == '\\' || $first == '[' || $first == '/' ) {
// potential UNC path, wikilink, absolute or relative path
$hrefValue = '#InvalidLink';
$badHtml .= Linker::makeExternalLink( $hrefValue, $textValue ) . ', ';
$textValue = 'Invalid link. Check Graphviz source.';
}
else {
$title = Title::newFromText( $hrefValue );
if ( is_null( $title ) ) {
// invalid link
$hrefValue = '#InvalidLink';
$badHtml .= Linker::makeExternalLink( $hrefValue, $textValue ) . ', ';
$textValue = 'Invalid link. Check Graphviz source.';
}
else {
// internal link
$parser->mOutput->addLink( $title );
$intHtml .= Linker::link( $title, $textValue ) . ', ';
$hrefValue = $title->getFullURL();
}
}
}
$areaNode->attributes()->href = $hrefValue;
$areaNode->attributes()->title = $textValue;
}
$map = $xmlObj->asXML();
// The contents of $map, which is now XML, gets embedded
// in the HTML sent to the browser so we need to strip
// the XML version tag and we also strip the <map> because
// it will get replaced with a new one with the correct name.
$map = str_replace( '<?xml version="1.0"?>', '', $map );
$map = preg_replace( '#<ma(.*)>#', ' ', $map );
$map = str_replace( '</map>', '', $map );
// Let's see what it looks like now that we are done with it.
wfDebugLog( 'graphviz', 'map after: ' . $map . "\n" );
$txt = '' .
'<table style="background-color:#f9f9f9;border:1px solid #ddd;">' .
'<tr>' .
'<td style="border:1px solid #ddd;text-align:center;">' .
'<map name="' . $storagename . '">' . $map . '</map>' .
'<img src="' . $wgUploadPath . '/graphviz/' . $storagename . '.' . $outputType . '"' . ' usemap="#' . $storagename . '" />' .
'</td>' .
'</tr>' .
'<tr>' .
'<td style="font:10px verdana;">' .
'This Graphviz diagram links to the following pages:' .
'<br /><strong>Internal</strong>: ' . ( $intHtml != '' ? rtrim( $intHtml, ' ,' ) : '<em>none</em>' ) .
'<br /><strong>External</strong>: ' . ( $extHtml != '' ? rtrim( $extHtml, ' ,' ) : '<em>none</em>' ) .
( $badHtml != '' ? '<br /><strong>Invalid</strong>: ' . rtrim($badHtml, ' ,') .
'<br /><em>Tip: Do not use wikilinks ([]), UNC paths (\\) or relative links (/) when creating links in Graphviz diagrams.</em>' : '' ) .
'</td>' .
'</tr>' .
'</table>';
Possible enhancements:
It would be nice if the list of links below the graph were sorted and de-duped.
I've searched and searched. I can't find the solution. I have a string that goes a little something like this: ABC_test 001-2.jpg
I also have this bit of code:
$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", " ", $replaceUnder);
However, this bit of code will not replace the underscore (_). In fact, the output of this variable is: ABC
So it stops once it hits the underscore. I need to replace EVERY possible non-alphanumeric character, including the underscore, asterisks, question marks, whatever. What am I missing?
Thanks for the help.
EDIT:
<?php
//set images directory
$directory = 'ui/images/customFabrication/';
try {
// create slideshow div to be manipulated by the above jquery function
echo "<div class=\"slideLeft\"></div>";
echo "<div class=\"sliderWindow\">";
echo "<ul id=\"slider\">";
//iterate through the directory, get images, set the path and echo them in img tags.
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . "" . $item;
$class = substr($item, 0,-4); //removes file type from file name
//$replaceUnder = str_replace("_", "-", $class);
$makeDash = str_replace(" ", "-", $replaceUnder);
$replaceUnder = preg_replace("/[^a-zA-Z0-9\s]/", " ", $class);
//$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", " ", $replaceUnder);
echo "<li><img rel=" . $replaceUnder . " class=" . $class . " src=\"/ui/js/timthumb.php?src=/" . $path . "&h=180&w=230&zc=1\" /></li>";
}
}
echo "</ul>";
echo "</div>";
echo "<div class=\"slideRight\"></div>";
}
//if directory is empty throw an exception.
catch(Exception $exc) {
echo 'the directory you chose seems to be empty';
}
?>
I can't reproduce your problem, for me the string that gets outputted is:
$replaceUnder = 'ABC_test 001-2.jpg';
$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", " ", $replaceUnder);
print_r($makeSpace);
# output:
# ABC test 001 2 jpg
.
dubugging your code
I went through the code you pasted in and found a few errors, which are maybe related, maybe not:
I get an error on this line, because replaceUnder is not defined:
$makeDash = str_replace(" ", "-", $replaceUnder);
since you commented this line out:
//$replaceUnder = str_replace("_", "-", $class);
I guess you meant to comment it out as well. It's not clear at all what you're trying to do and why you have all those replace statements. If you're just trying to echo out the file names with all the symbols replaced, this is how I did it and the letters all got replaced with spaces:
<?php
//set images directory
$directory = './';
try {
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . "" . $item;
// remove ending/filetype - the other method doesn't support 4 letter file endings
$name = basename($item);
$fixedName = preg_replace("/[^a-zA-Z0-9\s]/", " ", $name);
echo "Name: $fixedName\n";
}
}
}
//if directory is empty throw an exception.
catch(Exception $exc) {
echo 'the directory you chose seems to be empty';
}
?>
I think your whole problems stem from the naming of variables. Consider turning on notice errors - they will let you know if you're referencing variables that aren't defined.